import random
import time
from datetime import datetime
from io import BytesIO
from urllib.parse import unquote
import xlwt
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.core.paginator import Paginator, EmptyPage
from django.http import HttpResponse, JsonResponse
from django.shortcuts import redirect
from django.core.paginator import PageNotAnInteger
from django.shortcuts import render
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt

from app01.models import Cases
from django.core.exceptions import ValidationError
from django.core.exceptions import ObjectDoesNotExist
from .utils import pare_wise, deal_with_multi_for_single, generate_search_case_1, deal_with_multi_options
from caseTemplate.models import Template
from projectManage.models import Project
from userManage.models import User


# @login_required(login_url='/login/')
def index(request):
    cases = Cases.objects.all().order_by("-id")
    p = request.GET.get('current_page', 1)
    p = int(p)
    paginator = Paginator(cases, 10)
    page_range = transfer_the_page_range(p, paginator)
    if paginator.num_pages - p > 5:
        last_page = True
    try:
        pages = paginator.page(p)
    except PageNotAnInteger:
        pages = paginator.page(1)
    except EmptyPage:
        pages = paginator.page(paginator.num_pages)
    return render(request, 'app01/index.html', locals())


def create_case(request):
    if request.method == 'POST':
        case_title = request.POST.get('case_title')
        pre_condition = request.POST.get('pre_condition')
        primary_module = request.POST.get('primary_module')
        sub_module = request.POST.get('sub_module')
        case_steps = request.POST.get('case_steps')
        creator = request.POST.get('creator')
        expect_result = request.POST.get('expect_result')
        remarks = request.POST.get('remarks')
        create_time = time.strftime('%Y-%m-%d %H:%M:%S')
        level = request.POST.get('level')
        level = int(level)
        case = Cases.objects.all()
        page_type = request.POST.get('page_type')
        case.create(
            title=case_title, pre_condition=pre_condition, case_steps=case_steps, case_level=level,
            primary_module=primary_module, sub_module=sub_module,
            creator=creator, expect_result=expect_result, create_time=create_time, remarks=remarks, page=page_type,

        )
        return redirect(reverse('app01:index'))


def edit_case(request):
    if request.method == 'POST':
        case_id = request.POST.get('case_id')
        case_id = int(case_id)
        case_title = request.POST.get('case_title')
        pre_condition = request.POST.get('pre_condition')
        case_steps = request.POST.get('case_steps')
        creator = request.POST.get('creator')
        create_time = request.POST.get('create_time')
        level = request.POST.get('level')
        level = int(level)
        expect_result = request.POST.get('expect_result')
        real_result = request.POST.get('real_result')
        remarks = request.POST.get('remarks')
        case = Cases.objects.filter(id=case_id)
        case.update(title=case_title, pre_condition=pre_condition, case_steps=case_steps,
                    creator=creator, create_time=create_time, expect_result=expect_result,
                    real_result=real_result, remarks=remarks, case_level=level)
    return redirect(reverse('app01:index'))


def generate_case(request):
    return HttpResponse("generate case")


def search_case(request):
    if request.method == 'GET':

        start_date = request.GET.get("start_date", '')
        end_date = request.GET.get("end_date", '')
        case_title = request.GET.get('case_title', '')
        case_title = case_title.strip()
        if start_date and end_date:
            search_result = Cases.objects.filter(Q(create_time__gte=start_date + " 00:00:00") &
                                                 Q(create_time__lte=end_date + " 23:59:59"),
                                                 title__contains=case_title).order_by('-id')
        elif start_date:
            search_result = Cases.objects.filter(create_time__gte=start_date + " 00:00:00",
                                                 title__contains=case_title).order_by('-id')
        elif end_date:
            search_result = Cases.objects.filter(create_time__lte=end_date + " 23:59:59",
                                                 title__contains=case_title).order_by('-id')
        else:
            search_result = Cases.objects.filter(title__contains=case_title).order_by('-id')
        p = request.GET.get('current_page', 1)
        p = int(p)
        paginator = Paginator(search_result, 10)
        page_range = transfer_the_page_range(p, paginator)
        if paginator.num_pages - p > 5:
            last_page = True
        try:
            pages = paginator.page(p)
        except PageNotAnInteger:
            pages = paginator.page(1)
        except EmptyPage:
            pages = paginator.page(paginator.num_pages)
        return render(request, 'app01/search_result.html', locals())


def jump_to_index(request):
    return redirect(reverse('app01:new_page'))


def transfer_the_page_range(p, paginator):
    """
    页数进行转换
    :param p:
    :param paginator:
    :return:
    """
    if paginator.num_pages > 5:
        if p - 5 < 1:
            if paginator.num_pages > 10:
                page_range = range(1, 11)
            else:
                page_range = range(1, paginator.num_pages + 1)
        elif p + 5 > paginator.num_pages:
            page_range = range(p - 5, paginator.num_pages + 1)
        else:
            page_range = range(p - 5, p + 5)
    else:
        page_range = paginator.page_range
    return page_range


def new_page(request):
    cases = Cases.objects.all().filter(page='新增').order_by("-id")
    p = request.GET.get('current_page', 1)
    paginator = Paginator(cases, 10)
    p = int(p)
    projects = Project.objects.all()
    users = User.objects.all()
    page_range = transfer_the_page_range(p, paginator)
    if paginator.num_pages - p > 5:
        last_page = True
    try:
        pages = paginator.page(p)
    except PageNotAnInteger:
        pages = paginator.page(1)
    except EmptyPage:
        pages = paginator.page(paginator.num_pages)
    return render(request, 'app01/new_page.html', locals())


def new_page_create_case(request):
    if request.method == 'POST':
        case_title = request.POST.get('case_title')
        pre_condition = request.POST.get('pre_condition')
        primary_module = request.POST.get('primary_module')
        sub_module = request.POST.get('sub_module')
        case_steps = request.POST.get('case_steps')
        creator = request.POST.get('creator')
        expect_result = request.POST.get('expect_result')
        remarks = request.POST.get('remarks')
        create_time = time.strftime('%Y-%m-%d %H:%M:%S')
        level = request.POST.get('level')
        level = int(level)
        case = Cases.objects.all()
        project_name = request.POST.get('project_name')
        try:

            project_id = Project.objects.get(project_name__exact=project_name).id
            case.create(
                title=case_title, pre_condition=pre_condition, case_steps=case_steps, case_level=level,
                creator=creator, expect_result=expect_result, create_time=create_time, remarks=remarks, page='新增',
                project_id=project_id, primary_module=primary_module, sub_module=sub_module
            )
            return redirect(reverse('app01:new_page'))
        except Exception as error1:
            print(error1)
            return HttpResponse("项目名称不存在，已修改后再次提交！")
    else:
        return HttpResponse("demo")


def new_page_delete(request, case_id):
    Cases.objects.get(pk=case_id).delete()
    referer = request.headers.get('Referer')
    return redirect(referer)


def new_page_edit_case(request):
    if request.method == 'POST':
        referer = request.headers.get('Referer')
        case_id = request.POST.get('case_id')
        case_id = int(case_id)
        case_title = request.POST.get('case_title')
        primary_module = request.POST.get('primary_module')
        sub_module = request.POST.get('sub_module')
        pre_condition = request.POST.get('pre_condition')
        case_steps = request.POST.get('case_steps')
        creator = request.POST.get('creator')
        project_name = request.POST.get('project_name')
        create_time = request.POST.get('create_time')
        level = request.POST.get('level')
        level = int(level)
        expect_result = request.POST.get('expect_result')
        real_result = request.POST.get('real_result')
        remarks = request.POST.get('remarks')
        case = Cases.objects.filter(id=case_id)
        try:

            project_id = Project.objects.get(project_name__exact=project_name).id
            case.update(
                title=case_title, pre_condition=pre_condition, case_steps=case_steps, case_level=level,
                creator=creator, expect_result=expect_result, create_time=create_time, remarks=remarks, page='新增',
                project_id=project_id, real_result=real_result, primary_module=primary_module, sub_module=sub_module,
            )
            return redirect(referer)
        except Exception as error1:
            print(error1)
            return HttpResponse("项目名称不存在，已修改后再次提交！")


def new_page_search_case(request):
    try:
        if request.method == 'GET':
            start_date = request.GET.get("start_date", '')
            end_date = request.GET.get("end_date", '')
            case_title = request.GET.get('case_title', '')
            case_title = case_title.strip()
            case_creator = request.GET.get('case_creator', '')
            case_creator = case_creator.strip()
            if start_date and end_date:
                search_result = Cases.objects.filter(Q(create_time__gte=start_date + " 00:00:00") &
                                                     Q(create_time__lte=end_date + " 23:59:59"),
                                                     title__contains=case_title, page='新增',
                                                     creator__contains=case_creator).order_by('-id')
            elif start_date:
                search_result = Cases.objects.filter(create_time__gte=start_date + " 00:00:00",
                                                     title__contains=case_title, page='新增',
                                                     creator__contains=case_creator).order_by('-id')
            elif end_date:
                search_result = Cases.objects.filter(create_time__lte=end_date + " 23:59:59",
                                                     title__contains=case_title, page='新增',
                                                     creator__contains=case_creator).order_by('-id')
            else:
                search_result = Cases.objects.filter(title__contains=case_title, page='新增',
                                                     creator__contains=case_creator).order_by('-id')
            p = request.GET.get('current_page', 1)
            p = int(p)
            paginator = Paginator(search_result, 10)
            page_range = transfer_the_page_range(p, paginator)
            if paginator.num_pages - p > 5:
                last_page = True
            try:
                pages = paginator.page(p)
            except PageNotAnInteger:
                pages = paginator.page(1)
            except EmptyPage:
                pages = paginator.page(paginator.num_pages)
            return render(request, 'app01/new_page_search.html', locals())
    except ValidationError as error1:
        return render(request, 'app01/500_error.html', {"error_message": "年份不能超过4位数"})


def new_page_generate_case(request):
    if request.method == 'POST':
        total_len = len(request.POST)
        module = ""
        field = ""
        is_ui_case_needed = request.POST.get('ui_case')

        n = 4
        case_creator = request.POST.get("creator", '')
        case_system = request.POST.get("auth", '')
        project = Project.objects.get(project_name=case_system)

        project_id = project.id
        page_name = request.POST.get('page_name', '')
        primary_module = None
        sub_module = []
        for i in range(1, 100):
            dict_key = f'module{i}'
            if dict_key in request.POST:
                if dict_key == 'module1':
                    primary_module = request.POST.get(dict_key)
                else:
                    if request.POST.get(dict_key):
                        sub_module.append(request.POST.get(dict_key))
                if request.POST.get(dict_key):
                    n += 1
                    module += request.POST.get(dict_key) + ">>"
            else:
                break
        if sub_module:
            sub_module = ">>".join(sub_module)
        for i in range(1, 100):
            dict_key = f'field{i}'
            if dict_key in request.POST:
                n += 1
                field += request.POST.get(dict_key)
            else:
                break
        left_len = total_len - n
        groups = left_len // 8
        print("有几个字段", groups)
        case = Cases.objects.all()
        case_precondition = f"已登录{case_system}"
        case_common_title = []
        case_common_steps = []
        case_common_expect_result = []
        for i in range(groups + 1):
            """
            1.进入【模块】2.【字段名】是否存在3.【字段名】为必填---a.字段名为空，给出提示4.【枚举值无】5.【字段名】输入大于【max】，给出提示不能大于max
             'field_name1': [''], 'field_type1': [''], 'enums1': ['无'], 'default_value1': [''], 'required1': [''], 
             'edit1': [''], 'max1': [''], 'remarks1': [''], 'case_level1': ['1']
            """
            field_name = request.POST.get(f'field_name{i}')
            field_type = request.POST.get(f'field_type{i}')
            field_required = request.POST.get(f'required{i}')
            field_min = request.POST.get(f'min{i}')
            field_digit_num = request.POST.get(f'digitNum{i}')
            if field_digit_num:
                field_digit_num = int(field_digit_num)
            if field_min:
                field_min = int(field_min)
            field_max = request.POST.get(f'max{i}')
            if field_max:
                field_max = int(field_max)
            display = request.POST.get(f"display{i}")
            field_default = request.POST.get(f'default_value{i}')
            case_1_pre_condition = f"已登录{case_system}"
            case_level = request.POST.get(f'case_level{i}')
            if case_level:
                case_level = int(case_level)
            # TODO case_level
            case_precondition = case_1_pre_condition
            case_enums = request.POST.get(f'enums{i}')
            if field_name:

                if field_type == "文本":
                    """
                        1. 文本：可输入字母和数字
                        2. 纯数字：只能输入数字
                    """
                    case_text_title = []
                    case_text_steps = []
                    case_text_expect_result = []
                    if field_min:
                        case_text_title += [
                            f"{field_name}输入{field_min + 1}个字符",
                            f"{field_name}输入{field_min - 1}个字符",
                            f"{field_name}输入{field_min}个字符",
                        ]
                        case_text_steps += [
                            f"1.进入{module}{page_name}页面；2.{field_name}输入{field_min + 1}个字符；",
                            f"1.进入{module}{page_name}页面；2.{field_name}输入超过{field_min - 1}个字符；",
                            f"1.进入{module}{page_name}页面；2.{field_name}输入{field_min}个字符；",
                        ]
                        case_text_expect_result += [
                            f"提示{field_name}不能超过{field_min}个字符",
                            f"可正常保存",
                            f"可正常保存",
                        ]
                    if field_max:
                        case_text_title += [
                            f"{field_name}输入{field_max + 1}个字符",
                            f"{field_name}输入{field_max - 1}个字符",
                            f"{field_name}输入{field_max}个字符",
                        ]
                        case_text_steps += [
                            f"1.进入{module}{page_name}页面；2.{field_name}输入{field_max + 1}个字符；",
                            f"1.进入{module}{page_name}页面；2.{field_name}输入超过{field_max - 1}个字符；",
                            f"1.进入{module}{page_name}页面；2.{field_name}输入{field_max}个字符；",
                        ]
                        case_text_expect_result += [
                            f"提示{field_name}不能超过{field_max}个字符",
                            f"可正常保存",
                            f"可正常保存",
                        ]
                    if field_min and field_max:
                        if field_min < field_max:
                            for _ in range(2):
                                num = random.randint(field_min, field_max)
                                case_text_title += [f'{field_name}输入{num}个字符']
                                case_text_steps += [
                                    f"1.进入{module}{page_name}页面；2.{field_name}输入{num}个字符；",
                                ]
                                case_text_expect_result += ["可正常保存"]
                        else:
                            error_message = f"{field_name}的左边界值应小于右边界值"
                            return render(request, 'app01/newRowError.html', {"error_message": error_message})
                    case_text_title += [
                        f"{field_name}输入字符串中含空格",
                        f"{field_name}输入字符串首尾含空格",
                        f"{field_name}输入特殊字符",
                        f"{field_name}输入html格式字符",
                        f"{field_name}输入NULL或null字符串",
                        f"{field_name}输入普通字符串",
                    ]
                    case_text_steps += [
                        f"1.进入{module}{page_name}页面；2.{field_name}输入字符串中含空格；",
                        f"1.进入{module}{page_name}页面；2.{field_name}输入字符串首尾含空格；",
                        f"1.进入{module}{page_name}页面；2.{field_name}输入特殊字符，如~!@#$%^&*()_+|=-\\`[];’”:,./?<>；",
                        f"1.进入{module}{page_name}页面；2.{field_name}输入html格式字符,如<script>alert(/xss/)</script>；",
                        f"1.进入{module}{page_name}页面；2.{field_name}输入NULL或null字符串；",
                        f"1.进入{module}{page_name}页面；2.{field_name}输入普通字符串；",

                    ]
                    case_text_expect_result += [
                        "保存成功",
                        "自动过滤首尾空格，保存成功",
                        "保存成功，显示无异常",
                        "保存成功，显示无异常",
                        "保存成功",
                        "保存成功",
                    ]
                    for _ in range(len(case_text_title)):
                        case.create(
                            title=case_text_title[_], pre_condition=case_1_pre_condition, case_steps=case_text_steps[_],
                            case_level=case_level, creator=case_creator, expect_result=case_text_expect_result[_],
                            create_time=time.strftime("%Y-%m-%d %H:%M:%S"), primary_module=primary_module, sub_module=sub_module,
                            remarks='', page='新增', project_id=project_id,
                        )
                elif field_type == '数字':
                    case_num1_title = []
                    case_num1_expect_result = []
                    case_num1_steps = []
                    case_num1_create_time = time.strftime('%Y-%m-%d %H:%M:%S')
                    if field_min:
                        case_num1_title += [
                            f'{field_name}输入{field_min - 1}',
                            f'{field_name}输入{field_min}',
                            f'{field_name}输入{field_min + 1}',
                        ]
                        case_num1_steps += [
                            f'1.进入{module}{page_name}页面；2.{field_name}输入{field_min - 1}；',
                            f'1.进入{module}{page_name}页面；2.{field_name}输入{field_min}；',
                            f'1.进入{module}{page_name}页面；2.{field_name}输入{field_min + 1}；',
                        ]
                        case_num1_expect_result += [
                            f"提示{field_name}不能小于{field_min}",
                            f"可正常保存",
                            f"可正常保存",
                        ]
                    if field_max:
                        case_num1_title += [
                            f'{field_name}输入{field_max + 1}',
                            f'{field_name}输入{field_max}',
                            f'{field_name}输入{field_max - 1}',
                        ]
                        case_num1_steps += [
                            f'1.进入{module}{page_name}页面；2.{field_name}输入{field_max + 1}；',
                            f'1.进入{module}{page_name}页面；2.{field_name}输入{field_max}；',
                            f'1.进入{module}{page_name}页面；2.{field_name}输入{field_max - 1}；',
                        ]
                        case_num1_expect_result += [
                            f"提示{field_name}不能大于{field_max}",
                            "可正常保存",
                            "可正常保存",
                        ]
                    if field_min and field_max:
                        if field_min < field_max:
                            random_list = []
                            for _ in range(3):
                                num = random.randint(field_min, field_max)
                                random_list.append(num)
                                case_num1_title += [f'{field_name}输入{num}']
                                case_num1_steps += [
                                    f'1.进入{module}{page_name}页面；2.{field_name}输入{num}；',
                                ]
                                case_num1_expect_result += ["可正常保存"]
                        else:
                            error_message = f"{field_name}的左边界值应小于右边界值"
                            return render(request, 'app01/newRowError.html', {"error_message": error_message})

                    if field_digit_num:
                        case_num1_title += [
                            f'{field_name}输入{field_digit_num + 1}位数的值',
                            f'{field_name}输入{field_digit_num - 1}位数的值',
                            f'{field_name}输入{field_digit_num}位数的值',
                        ]
                        case_num1_steps += [
                            f'1.进入{module}{page_name}页面；2.{field_name}输入{field_digit_num + 1}位数的值；',
                            f'1.进入{module}{page_name}页面；2.{field_name}输入{field_digit_num}位数的值；',
                            f'1.进入{module}{page_name}页面；2.{field_name}输入{field_digit_num - 1}位数的值；',
                        ]
                        case_num1_expect_result += [
                            f'无法输入或给出错误提示,{field_name}的位数不能大于{field_digit_num}',
                            '保存成功，无错误提示',
                            '保存成功，无错误提示',
                        ]
                    for i in range(len(case_num1_title)):
                        case.create(
                            title=case_num1_title[i], pre_condition=case_1_pre_condition,
                            case_steps=case_num1_steps[i], primary_module=primary_module, sub_module=sub_module,
                            case_level=case_level, creator=case_creator,
                            expect_result=case_num1_expect_result[i], project_id=project_id,
                            create_time=case_num1_create_time, remarks='', page='新增'
                        )
                elif field_type == '邮箱':
                    case_email_title = []
                    case_email_steps = []
                    case_email_expect_result = []
                    case_email_create_time = time.strftime('%Y-%m-%d %H:%M:%S')
                    if field_min:
                        case_email_title += [
                            f"{field_name}输入长度为{field_min - 1}的邮箱名",
                            f"{field_name}输入长度为{field_min}的邮箱名",
                            f"{field_name}输入长度为{field_min + 1}的邮箱名",
                        ]
                        case_email_steps += [
                            f'1.进入{module}{page_name}页面；2.{field_name}输入长度为{field_min - 1}的邮箱名；3.其他输入正确',
                            f'1.进入{module}{page_name}页面；2.{field_name}输入长度为{field_min}的邮箱名；3.其他输入正确',
                            f'1.进入{module}{page_name}页面；2.{field_name}输入长度为{field_min + 1}的邮箱名；3.其他输入正确',
                        ]
                        case_email_expect_result += [
                            f"提示邮箱名长度不能少于{field_min}位",
                            f'保存成功，无错误提示',
                            f'保存成功，无错误提示',
                        ]
                    if field_max:
                        case_email_title += [
                            f"{field_name}输入长度为{field_max - 1}的邮箱名",
                            f"{field_name}输入长度为{field_max}的邮箱名",
                            f"{field_name}输入长度为{field_max + 1}的邮箱名",
                        ]
                        case_email_steps += [
                            f'1.进入{module}{page_name}页面；2.{field_name}输入长度为{field_max - 1}的邮箱名；3.其他输入正确',
                            f'1.进入{module}{page_name}页面；2.{field_name}输入长度为{field_max}的邮箱名；3.其他输入正确',
                            f'1.进入{module}{page_name}页面；2.{field_name}输入长度为{field_max + 1}的邮箱名；3.其他输入正确',
                        ]
                        case_email_expect_result += [
                            f"保存成功，无错误提示",
                            f'保存成功，无错误提示',
                            f'提示邮箱名长度不能多于{field_max}位',
                        ]
                    if field_min and field_max:
                        if field_min < field_max:
                            random_list = []
                            for _ in range(1):
                                num = random.randint(field_min, field_max)
                                random_list.append(num)
                                case_email_title += [f'{field_name}输入长度为{num}的邮箱名']
                                case_email_steps += [
                                    f'1.进入{module}{page_name}页面；2.{field_name}长度为{num}的邮箱名；',
                                ]
                                case_email_expect_result += ["无错误提示"]
                        else:
                            error_message = f"{field_name}的左边界值应小于右边界值"
                            return render(request, 'app01/newRowError.html', {"error_message": error_message})
                    case_email_title += [
                        f'{field_name}输入无@的邮箱格式',
                        f'{field_name}输入@前无内容的邮箱格式',
                        f'{field_name}输入@后无内容的邮箱格式',
                        f'{field_name}输入正确的邮箱格式',

                    ]
                    case_email_steps += [
                        f'1.进入{module}{page_name}页面；2.{field_name}输入无@的邮箱格式，如ab.com；3.其他输入正确。',
                        f'1.进入{module}{page_name}页面；2.{field_name}输入@前无内容的邮箱格式，如@b.com；3.其他输入正确。',
                        f'1.进入{module}{page_name}页面；2.{field_name}输入@后无内容的邮箱格式，如a@.com；3.其他输入正确。',
                        f'1.进入{module}{page_name}页面；2.{field_name}输入@后无内容的邮箱格式，如zhangsan@126.com；3.其他输入正确。',
                    ]
                    case_email_expect_result += [
                        f'提示邮箱格式错误',
                        f'提示邮箱格式错误',
                        f'提示邮箱格式错误',
                        f'保存成功，无错误提示',
                    ]
                    for _ in range(len(case_email_title)):
                        case.create(
                            title=case_email_title[_], pre_condition=case_1_pre_condition,
                            case_steps=case_email_steps[_], primary_module=primary_module, sub_module=sub_module,
                            case_level=case_level, creator=case_creator,
                            expect_result=case_email_expect_result[_],
                            create_time=case_email_create_time, remarks='', page='新增', project_id=project_id
                        )
                elif field_type == '日期':
                    case_date_title = []
                    case_date_steps = []
                    case_date_expect_result = []
                    case_date_title += [
                        f'{field_name}月份输入小于等于0',
                        f'{field_name}月份输入大于等于13',
                        f'{field_name}月份输入大于0小于13',
                        f'{field_name}月份输入汉字',
                        f'{field_name}月份输入特殊字符',
                        f'{field_name}月份输入英文字符',
                        f'{field_name}日数，大月输入小于等于31的值',
                        f'{field_name}日数，小于输入小于等于30的值',
                        f'{field_name}日数，大月输入大于31的整数',
                        f'{field_name}日数，大月输入大于30的整数',
                        f'{field_name}日数，非闰年2月输入大于28的整数',
                        f'{field_name}日数，非闰年2月输入小于等于28的正整数',
                        f'{field_name}日数，闰年2月输入小于等于29的正整数',
                        f'{field_name}日数，闰年2月输入大于29的整数',
                        f'{field_name}日数输入汉字',
                        f'{field_name}日数输入特殊字符',
                        f'{field_name}日数输入英文字符',
                        f'{field_name}年份输入大于4位整数',
                        f'{field_name}年份输入小于4位整数',
                        f'{field_name}年份输入4位整数',
                        f'{field_name}年份输入汉字',
                        f'{field_name}年份输入特殊字符',
                        f'{field_name}年份输入英文字符',
                    ]
                    case_date_steps += [
                        f'1.进入{module}{page_name}页面；2.{field_name}月份输入-1',
                        f'1.进入{module}{page_name}页面；2.{field_name}月份输入13',
                        f'1.进入{module}{page_name}页面；2.{field_name}月份输入6；3.其他输入正确',
                        f'1.进入{module}{page_name}页面；2.{field_name}月份输入测试',
                        f'1.进入{module}{page_name}页面；2.{field_name}月份输入特殊符合-!@#$%^&*().',
                        f'1.进入{module}{page_name}页面；2.{field_name}月份输入test',
                        f'1.进入{module}{page_name}页面；2.{field_name}月份输入1，日输入31；3.其他输入正确',
                        f'1.进入{module}{page_name}页面；2.{field_name}月份输入4，日输入30；3.其他输入正确',
                        f'1.进入{module}{page_name}页面；2.{field_name}月份输入1，日输入32',
                        f'1.进入{module}{page_name}页面；2.{field_name}月份输入4，日输入31',
                        f'1.进入{module}{page_name}页面；2.{field_name}年输入2022，月份输入2，日输入29',
                        f'1.进入{module}{page_name}页面；2.{field_name}年输入2022，月份输入2，日输入28；3.其他输入正确',
                        f'1.进入{module}{page_name}页面；2.{field_name}年输入2020，月份输入2，日输入29；3.其他输入正确',
                        f'1.进入{module}{page_name}页面；2.{field_name}年输入2020，月份输入2，日输入30',
                        f'1.进入{module}{page_name}页面；2.{field_name}日数输入测试',
                        f'1.进入{module}{page_name}页面；2.{field_name}日数输入特殊符合-!@#$%^&*().',
                        f'1.进入{module}{page_name}页面；2.{field_name}日数输入test',
                        f'1.进入{module}{page_name}页面；2.{field_name}年输入10000',
                        f'1.进入{module}{page_name}页面；2.{field_name}年输入100',
                        f'1.进入{module}{page_name}页面；2.{field_name}年输入2022；3.其他输入正确',
                        f'1.进入{module}{page_name}页面；2.{field_name}年份输入测试',
                        f'1.进入{module}{page_name}页面；2.{field_name}年份输入特殊符合-!@#$%^&*().',
                        f'1.进入{module}{page_name}页面；2.{field_name}年份输入test',
                    ]
                    case_date_expect_result += [
                        f'小于等于0的月份自动更新为1或给出错误提示，{field_name}月份不能小于等于0',
                        f'大于等于13的月份自动更新为12或给出错误提示，{field_name}月份不能大于等于13',
                        f'可正常保存，无错误提示',
                        f'汉字无法写入或给出错误提示，{field_name}月份为1-12的正整数',
                        f'特殊字符无法写入或给出错误提示，{field_name}月份为1-12的正整数',
                        f'英文字符无法写入或给出错误提示，{field_name}月份为1-12的正整数',
                        '可正常保存，无错误提示',
                        '可正常保存，无错误提示',
                        f'大月日数大于31自动更新为31或给出错误提示，{field_name}大月日数不能大于31',
                        f'小月日数大于30自动更新为30或给出错误提示，{field_name}小月日数不能大于30',
                        f'非闰年2月大于28的日数自动更新为28或给出错误提示，{field_name}非闰年2月日数不能大于28',
                        '可正常保存，无错误提示',
                        '可正常保存，无错误提示',
                        f'闰年2月大于29的日数自动更新为29或给出错误提示，{field_name}闰年2月日数不能大于29',
                        f'汉字无法写入或给出错误提示，{field_name}日数为正整数',
                        f'特殊字符无法写入或给出错误提示，{field_name}日数为正整数',
                        f'英文字符无法写入或给出错误提示，{field_name}日数为正整数',
                        f'无法输入或给出错误提示，{field_name}年份位数不能大于4',
                        f'自动在输入前补一位0或给出错误提示，{field_name}年份位数不能小于4',
                        '可正常保存，无错误提示',
                        f'汉字无法写入或给出错误提示，{field_name}年份为位数为4的正整数',
                        f'特殊字符无法写入或给出错误提示，{field_name}年份为位数为4的正整数',
                        f'英文字符无法写入或给出错误提示，{field_name}年份为位数为4的正整数',
                    ]
                    for _ in range(len(case_date_title)):
                        case.create(
                            title=case_date_title[_], pre_condition=case_1_pre_condition,
                            case_steps=case_date_steps[_], primary_module=primary_module, sub_module=sub_module,
                            case_level=case_level, creator=case_creator,
                            expect_result=case_date_expect_result[_], project_id=project_id,
                            create_time=time.strftime("%Y-%m-%d %H:%M:%S"), remarks='', page='新增'
                        )
                elif field_type == '时间':
                    case_time_title = []
                    case_time_steps = []
                    case_time_expect_result = []
                    case_time_title += [
                        f'{field_name}的时输入24',
                        f'{field_name}的时输入00',
                        f'{field_name}时输入汉字',
                        f'{field_name}时输入字母',
                        f'{field_name}时输入特殊符号',
                        f'{field_name}的分输入60',
                        f'{field_name}的分输入59',
                        f'{field_name}的分输入00',
                        f'{field_name}的分输入汉字',
                        f'{field_name}的分输入字母',
                        f'{field_name}的分输入特殊符号',
                        f'{field_name}的秒输入60',
                        f'{field_name}的秒输入59',
                        f'{field_name}的秒输入00',
                        f'{field_name}的秒输入汉字',
                        f'{field_name}的秒输入字母',
                        f'{field_name}的秒输入特殊符号',
                    ]
                    case_time_steps += [
                        f'1.进入{module}{page_name}页面；2.{field_name}的时输入24',
                        f'1.进入{module}{page_name}页面；2.{field_name}的时输入00；3.其他输入正确',
                        f'1.进入{module}{page_name}页面；2.{field_name}的时输入测试',
                        f'1.进入{module}{page_name}页面；2.{field_name}的时输入test',
                        f'1.进入{module}{page_name}页面；2.{field_name}的时输入.*?!@#',
                        f'1.进入{module}{page_name}页面；2.{field_name}的分输入60',
                        f'1.进入{module}{page_name}页面；2.{field_name}的分输入59；3.其他输入正确',
                        f'1.进入{module}{page_name}页面；2.{field_name}的分输入00；3.其他输入正确',
                        f'1.进入{module}{page_name}页面；2.{field_name}的分输入测试',
                        f'1.进入{module}{page_name}页面；2.{field_name}的分输入test',
                        f'1.进入{module}{page_name}页面；2.{field_name}的分输入.*?!@#',
                        f'1.进入{module}{page_name}页面；2.{field_name}的秒输入60',
                        f'1.进入{module}{page_name}页面；2.{field_name}的秒输入59；3.其他输入正确',
                        f'1.进入{module}{page_name}页面；2.{field_name}的秒输入00；3.其他输入正确',
                        f'1.进入{module}{page_name}页面；2.{field_name}的秒输入测试',
                        f'1.进入{module}{page_name}页面；2.{field_name}的秒输入test',
                        f'1.进入{module}{page_name}页面；2.{field_name}的秒输入.*?!@#',

                    ]
                    case_time_expect_result += [
                        f"24自动转换为23或给出错误提示，时不能大于23",
                        f"正常保存，无错误提示",
                        f"无法输入或给出错误提示，时为0-23的整数",
                        f"无法输入或给出错误提示，时为0-23的整数",
                        f"无法输入或给出错误提示，时为0-23的整数",
                        f"60自动转换为59或给出错误提示，分不能大于59",
                        f"正常保存，无错误提示",
                        f"正常保存，无错误提示",
                        f"无法输入或给出错误提示，分为0-59的整数",
                        f"无法输入或给出错误提示，分为0-59的整数",
                        f"无法输入或给出错误提示，分为0-59的整数",
                        f"60自动转换为59或给出错误提示，秒不能大于59",
                        f"正常保存，无错误提示",
                        f"正常保存，无错误提示",
                        f"无法输入或给出错误提示，秒为0-59的整数",
                        f"无法输入或给出错误提示，秒为0-59的整数",
                        f"无法输入或给出错误提示，秒为0-59的整数",
                    ]
                    for _ in range(len(case_time_title)):
                        case.create(
                            title=case_time_title[_], pre_condition=case_1_pre_condition,
                            case_steps=case_time_steps[_], primary_module=primary_module, sub_module=sub_module,
                            case_level=case_level, creator=case_creator,
                            expect_result=case_time_expect_result[_], project_id=project_id,
                            create_time=time.strftime("%Y-%m-%d %H:%M:%S"), remarks='', page='新增'
                        )
                elif field_type == '密码':
                    case_pwd_title = []
                    case_pwd_steps = []
                    case_pwd_expect_result = []
                    case_pwd_title += [
                        f'{field_name}输入的密码密文显示'
                    ]
                    case_pwd_steps += [
                        f'1.进入{module}{page_name}页面；2.{field_name}输入密码',

                    ]
                    case_pwd_expect_result += [
                        f'{field_name}密文显示',
                    ]
                    for _ in range(len(case_pwd_title)):
                        case.create(
                            title=case_pwd_title[_], pre_condition=case_1_pre_condition,
                            case_steps=case_pwd_steps[_],
                            case_level=case_level, creator=case_creator,
                            expect_result=case_pwd_expect_result[_], project_id=project_id,
                            create_time=time.strftime("%Y-%m-%d %H:%M:%S"), remarks='', page='新增'
                        )
                elif field_type == '单选':
                    case_radio_title = []
                    case_radio_steps = []
                    case_radio_expect_result = []
                    case_radio_title += [
                        f"{field_name}同时选中多个",
                        f"{field_name}初始状态默认选中一个值",
                        f"{field_name}选项名和选项值检查",
                    ]
                    case_radio_steps += [
                        f"1.进入{module}{page_name}页面；2.对{field_name}进行同时选中多个选项的操作；",
                        f"1.进入{module}{page_name}页面；2.查看{field_name}初始状态是否默认选中一个值；",
                        f"1.进入{module}{page_name}页面；2.查看{field_name}的选项名和选项值是否符合设计要求",

                    ]
                    case_radio_expect_result += [
                        f"{field_name}同时只能选中一个选项",
                        f"{field_name}初始状态默认选中一个值，不能为空",
                        f"{field_name}的选项名和选项值符合设计要求",
                    ]
                    if case_enums:
                        try:
                            case_enums_list = case_enums.split(',')
                            for _ in case_enums_list:
                                case_radio_title += [f'{field_name}选中{_}，检查存入数据库的值']
                                case_radio_steps += [
                                    f"1.进入{module}{page_name}页面；2.{field_name}选中{_}；"
                                ]
                                case_radio_expect_result += [
                                    f'存入数据库的值与选项的值一致'
                                ]
                        except Exception as error1:
                            return render(request, 'app01/500_error.html', {'error_message': error1})
                    for _ in range(len(case_radio_title)):
                        case.create(
                            title=case_radio_title[_], pre_condition=case_1_pre_condition,
                            case_steps=case_radio_steps[_], primary_module=primary_module, sub_module=sub_module,
                            case_level=case_level, creator=case_creator,
                            expect_result=case_radio_expect_result[_], project_id=project_id,
                            create_time=time.strftime("%Y-%m-%d %H:%M:%S"), remarks='', page='新增'
                        )
                elif field_type == '多选':
                    case_checkbox_title = []
                    case_checkbox_steps = []
                    case_checkbox_expect_result = []
                    case_checkbox_title += [
                        f'{field_name}同时选中多个选项',
                        f'{field_name}同时都不选中'
                    ]
                    case_checkbox_steps += [
                        f"1.进入{module}{page_name}页面；2.对{field_name}进行同时选中多个选项的操作；3.查看数据库存入的数据",
                        f"1.进入{module}{page_name}页面；2.{field_name}的选项都不选中",

                    ]
                    case_checkbox_expect_result += [
                        f'同时被选中的选项存储到数据库中正确',
                        f'根据需求给出提示',
                    ]
                    if case_enums:
                        try:
                            case_enums_list = case_enums.split(',')
                            for _ in case_enums_list:
                                case_checkbox_title += [f'{field_name}选中{_}，检查存入数据库的值']
                                case_checkbox_steps += [
                                    f"1.进入{module}{page_name}页面；2.{field_name}选中{_}；"
                                ]
                                case_checkbox_expect_result += [
                                    f'存入数据库的值与选项的值一致'
                                ]
                        except Exception as error1:
                            return render(request, 'app01/500_error.html', {'error_message': error1})
                    for _ in range(len(case_checkbox_title)):
                        case.create(
                            title=case_checkbox_title[_], pre_condition=case_1_pre_condition,
                            case_steps=case_checkbox_steps[_], primary_module=primary_module, sub_module=sub_module,
                            case_level=int(case_level), creator=case_creator,
                            expect_result=case_checkbox_expect_result[_], project_id=project_id,
                            create_time=time.strftime("%Y-%m-%d %H:%M:%S"), remarks='', page='新增'
                        )
                if field_required == "是":
                    case_common_title += [
                        f"{field_name}字段输入英文空格",
                        f"{field_name}字段输入中文空格",
                    ]
                    case_common_steps += [
                        f"1.进入{module}{page_name}页面；2.{field_name}输入英文空格；3.其他输入正确。",
                        f"1.进入{module}{page_name}页面；2.{field_name}输入中文空格；3.其他输入正确。",
                    ]
                    case_common_expect_result += [
                        f"提示{field_name}不能为空",
                        f"提示{field_name}不能为空",
                    ]
                else:
                    case_common_title += [f"{field_name}字段输入英文空格",
                                          f"{field_name}字段输入中文空格",
                                          ]
                    case_common_steps += [
                        f"1.进入{module}{page_name}页面；2.{field_name}输入英文空格；3.其他输入正确。",
                        f"1.进入{module}{page_name}页面；2.{field_name}输入中文空格；3.其他输入正确。",
                    ]
                    case_common_expect_result += [
                        f"无错误提示",
                        f"无错误提示",
                    ]
                if display == "是":
                    case_common_title += [f"{field_name}在表格表头中展示"]
                    case_common_steps += [f"1.进入{module}{page_name}页面；2.查看{field_name}展示在表格表头"]
                    case_common_expect_result += [f"{field_name}在表格表头中展示"]
                else:
                    case_common_title += [f"{field_name}在表格表头中不展示"]
                    case_common_steps += [f"1.进入{module}{page_name}页面；2.查看{field_name}不展示在表格表头"]
                    case_common_expect_result += [f"{field_name}在表格表头中不展示"]
                if field_default:
                    case_common_title += [f"{field_name}默认值为{field_default}"]
                    case_common_steps += [f"1.进入{module}{page_name}页面；2.查看{field_name}的默认值为{field_default}"]
                    case_common_expect_result += [f"{field_name}默认值为{field_default}"]
                case_common_title += [f"{field_name}在{module}{page_name}页面可见"]
                case_common_steps += [f"进入{module}{page_name}页面, 查看{field_name}字段可见"]
                case_common_expect_result += [f"{field_name}在{module}{page_name}页面可见"]
        if is_ui_case_needed == '需要':
            case_common_title += [
                f"{module}{page_name}页面布局检查",
                f"{module}{page_name}页面设计风格检查",
                f"{module}{page_name}页面文字检查",
                f"{module}{page_name}页面输入框、按钮尺寸检查",
                f"{module}{page_name}页面不同分辨率显示情况检查",

            ]
            case_common_steps += [
                f"1.进入{module}{page_name}页面；2.检查页面的布局以及输入框和按钮是否对齐",
                f"1.进入{module}{page_name}页面；2.检查页面的设计风格是否与UI相符",
                f"1.进入{module}{page_name}页面；2.检查文字是否有错别字，描述是否简洁易懂",
                f"1.进入{module}{page_name}页面；2.检查输入框及按钮的长度和高度是否符合设计原型",
                f"1.进入{module}{page_name}页面；2.检查页面在不同分辨率的情况下程序显示是否正常",
            ]
            case_common_expect_result += [
                f'{module}{page_name}页面，布局合理，输入框和按钮对齐',
                f'{module}{page_name}页面，设计风格与UI相符',
                f'{module}{page_name}页面，无错别字，描述简洁易懂',
                f'{module}{page_name}页面，输入框及按钮的长度和高度符合设计要求',
                f'{module}{page_name}页面，不同分辨率的情况下程序显示正常',
            ]
        for _ in range(len(case_common_title)):
            case.create(
                title=case_common_title[_], pre_condition=case_precondition,
                case_steps=case_common_steps[_],
                case_level=1, creator=case_creator, primary_module=primary_module, sub_module=sub_module,
                expect_result=case_common_expect_result[_], project_id=project_id,
                create_time=time.strftime("%Y-%m-%d %H:%M:%S"), remarks='', page='新增'
            )

    return redirect(reverse('app01:new_row'))


def new_page_export_excel(request):
    # 导出excel数据
    # 设置HTTPResponse的类型
    cases = Cases.objects.all().filter(page__exact='新增')
    excel_postfix = time.strftime("%y%m%d%H%M%S")
    excel_name = f'filename=newPageCase_{excel_postfix}.xls'
    return export(excel_name, cases)


def export(excel_name, cases):
    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = f'attachment;{excel_name}'
    # 创建一个文件对象
    wb = xlwt.Workbook(encoding='utf8')
    # 创建一个sheet对象
    sheet = wb.add_sheet('new_page_sheet')

    # 设置文件头的样式,这个不是必须的可以根据自己的需求进行更改
    style_heading = xlwt.easyxf("""
            font:
                name Arial,
                colour_index white,
                bold on,
                height 0xA0;
            align:
                wrap off,
                vert center,
                horiz center;
            pattern:
                pattern solid,
                fore-colour 0x19;
            borders:
                left THIN,
                right THIN,
                top THIN,
                bottom THIN;
            """)

    # 写入文件标题
    sheet.write(0, 0, '序号', style_heading)
    sheet.write(0, 1, '主模块', style_heading)
    sheet.write(0, 2, '子模块', style_heading)
    sheet.write(0, 3, '用例标题', style_heading)
    sheet.write(0, 4, '前置条件', style_heading)
    sheet.write(0, 5, '用例步骤', style_heading)
    sheet.write(0, 6, '创建人', style_heading)
    sheet.write(0, 7, '创建时间', style_heading)
    sheet.write(0, 8, '用例等级', style_heading)
    sheet.write(0, 9, '预期结果', style_heading)
    sheet.write(0, 10, '实际结果', style_heading)
    sheet.write(0, 11, '备注', style_heading)

    # 写入数据
    data_row = 1
    # UserTable.objects.all()这个是查询条件,可以根据自己的实际需求做调整.
    for num, case in enumerate(cases.reverse()):
        # 格式化datetime
        create_time = case.create_time.strftime('%Y-%m-%d %H:%M:%S')
        sheet.write(data_row, 0, num + 1)
        sheet.write(data_row, 1, case.primary_module)
        sheet.write(data_row, 2, case.sub_module)
        sheet.write(data_row, 3, case.title)
        sheet.write(data_row, 4, case.pre_condition)
        sheet.write(data_row, 5, case.case_steps)
        sheet.write(data_row, 6, case.creator)
        sheet.write(data_row, 7, create_time)
        sheet.write(data_row, 8, case.case_level)
        sheet.write(data_row, 9, case.expect_result)
        sheet.write(data_row, 10, case.real_result)
        sheet.write(data_row, 11, case.remarks)
        data_row = data_row + 1

    # 写出到IO
    output = BytesIO()
    wb.save(output)
    # 重新定位到开始
    output.seek(0)
    response.write(output.getvalue())
    return response


def new_page_search_result_export(request):
    referer = request.headers.get('Referer')
    params_list = referer.split('&')
    params_dict = {}
    params_list = params_list[1:]
    for param in params_list:
        (key, value) = param.split('=')
        params_dict[key] = value
    start_date = params_dict['start_date']
    end_date = params_dict['end_date']
    case_title = params_dict['case_title']
    case_title = unquote(case_title, 'utf-8').strip("+")
    case_title = case_title.strip()
    case_creator = params_dict['case_creator']
    case_creator = unquote(case_creator, 'utf-8').strip("+")
    case_creator = case_creator.strip()
    if start_date and end_date:
        search_result = Cases.objects.filter(Q(create_time__gte=start_date + " 00:00:00") &
                                             Q(create_time__lte=end_date + " 23:59:59"),
                                             title__contains=case_title,
                                             creator__contains=case_creator,
                                             page__exact='新增').order_by('-id')
    elif start_date:
        search_result = Cases.objects.filter(create_time__gte=start_date + " 00:00:00",
                                             title__contains=case_title,
                                             creator__contains=case_creator,
                                             page__exact='新增').order_by('-id')
    elif end_date:
        search_result = Cases.objects.filter(create_time__lte=end_date + " 23:59:59",
                                             title__contains=case_title,
                                             creator__contains=case_creator,
                                             page__exact='新增').order_by('-id')
    else:
        search_result = Cases.objects.filter(title__contains=case_title,
                                             creator__contains=case_creator,
                                             page__exact='新增').order_by('-id')
    print(type(search_result))
    excel_postfix = time.strftime("%y%m%d%H%M%S")
    excel_name = f'filename=newPageCase_{excel_postfix}.xls'
    return export(excel_name, search_result)


def edit_page(request):
    cases = Cases.objects.all().filter(page='编辑').order_by("-id")
    p = request.GET.get('current_page', 1)
    p = int(p)
    projects = Project.objects.all()
    users = User.objects.all()
    paginator = Paginator(cases, 10)
    page_range = transfer_the_page_range(p, paginator)
    if paginator.num_pages - p > 5:
        last_page = True
    try:
        pages = paginator.page(p)
    except PageNotAnInteger:
        pages = paginator.page(1)
    except EmptyPage:
        pages = paginator.page(paginator.num_pages)
    return render(request, 'app01/edit_page.html', locals())


def edit_page_create_case(request):
    if request.method == 'POST':
        case_title = request.POST.get('case_title')
        pre_condition = request.POST.get('pre_condition')
        case_steps = request.POST.get('case_steps')
        creator = request.POST.get('creator')
        expect_result = request.POST.get('expect_result')
        remarks = request.POST.get('remarks')
        create_time = time.strftime('%Y-%m-%d %H:%M:%S')
        level = request.POST.get('level')
        level = int(level)
        case = Cases.objects.all()
        case_system = request.POST.get("project_name", '')

        project = Project.objects.get(project_name=case_system)
        project_id = project.id
        case.create(
            title=case_title, pre_condition=pre_condition, case_steps=case_steps, case_level=level,
            project_id=project_id,
            creator=creator, expect_result=expect_result, create_time=create_time, remarks=remarks, page='编辑'
        )
        return redirect(reverse('app01:edit_page'))


def edit_page_search_case(request):
    try:
        if request.method == 'GET':
            start_date = request.GET.get("start_date", '')
            end_date = request.GET.get("end_date", '')
            case_title = request.GET.get('case_title', '')
            case_title = case_title.strip()
            case_creator = request.GET.get('case_creator', '')
            case_creator = case_creator.strip()
            if start_date and end_date:
                search_result = Cases.objects.filter(Q(create_time__gte=start_date + " 00:00:00") &
                                                     Q(create_time__lte=end_date + " 23:59:59"),
                                                     title__contains=case_title, page='编辑',
                                                     creator__contains=case_creator).order_by('-id')
            elif start_date:
                search_result = Cases.objects.filter(create_time__gte=start_date + " 00:00:00",
                                                     title__contains=case_title, page='编辑',
                                                     creator__contains=case_creator).order_by('-id')
            elif end_date:
                search_result = Cases.objects.filter(create_time__lte=end_date + " 23:59:59",
                                                     title__contains=case_title, page='编辑',
                                                     creator__contains=case_creator).order_by('-id')
            else:
                search_result = Cases.objects.filter(title__contains=case_title, page='编辑',
                                                     creator__contains=case_creator).order_by('-id')
            p = request.GET.get('current_page', 1)
            p = int(p)
            paginator = Paginator(search_result, 10)
            page_range = transfer_the_page_range(p, paginator)
            if paginator.num_pages - p > 5:
                last_page = True
            try:
                pages = paginator.page(p)
            except PageNotAnInteger:
                pages = paginator.page(1)
            except EmptyPage:
                pages = paginator.page(paginator.num_pages)
            return render(request, 'app01/edit_page_search.html', locals())
    except ValidationError as error1:
        return render(request, 'app01/500_error.html', {"error_message": "年份不能超过4位数"})


def edit_page_edit_case(request):
    if request.method == 'POST':
        referer = request.headers.get('Referer')
        case_id = request.POST.get('case_id')
        case_id = int(case_id)
        case_title = request.POST.get('case_title')
        pre_condition = request.POST.get('pre_condition')
        case_steps = request.POST.get('case_steps')
        creator = request.POST.get('creator')
        project_name = request.POST.get('project_name')
        create_time = request.POST.get('create_time')
        level = request.POST.get('level')
        level = int(level)
        expect_result = request.POST.get('expect_result')
        real_result = request.POST.get('real_result')
        remarks = request.POST.get('remarks')
        case = Cases.objects.filter(id=case_id)
        try:

            project_id = Project.objects.get(project_name__exact=project_name).id
            case.update(
                title=case_title, pre_condition=pre_condition, case_steps=case_steps, case_level=level,
                creator=creator, expect_result=expect_result, create_time=create_time, remarks=remarks, page='编辑',
                project_id=project_id, real_result=real_result
            )
            return redirect(referer)
        except Exception as error1:
            print(error1)
            return HttpResponse("项目名称不存在，已修改后再次提交！")


def edit_page_delete(request, case_id):
    Cases.objects.get(pk=case_id).delete()
    referer = request.headers.get('Referer')
    return redirect(referer)


def edit_page_generate_case(request):
    if request.method == 'POST':
        total_len = len(request.POST)
        module = ""
        field = ""
        is_ui_case_needed = request.POST.get('ui_case')
        page_name = request.POST.get('page_name', '')
        n = 4
        case_creator = request.POST.get("creator", '')
        case_system = request.POST.get("auth", '')
        project = Project.objects.get(project_name=case_system)
        project_id = project.id
        primary_module = None
        sub_module = []
        for i in range(1, 100):
            dict_key = f'module{i}'
            if dict_key in request.POST:
                if dict_key == 'module0':
                    primary_module = request.POST.get(dict_key)
                else:
                    sub_module.append(request.POST.get(dict_key))
                if request.POST.get(dict_key):
                    n += 1
                    module += request.POST.get(dict_key) + ">>"
            else:
                break
        if sub_module:
            sub_module = ">>".join(sub_module)
        for i in range(1, 100):
            dict_key = f'field{i}'
            if dict_key in request.POST:
                n += 1
                field += request.POST.get(dict_key)
            else:
                break
        left_len = total_len - n
        groups = left_len // 8
        print("有几个字段", groups)
        case = Cases.objects.all()
        case_precondition = f"已登录{case_system}"
        case_common_title = []
        case_common_steps = []
        case_common_expect_result = []
        for i in range(groups + 1):
            """
            1.进入【模块】2.【字段名】是否存在3.【字段名】为必填---a.字段名为空，给出提示4.【枚举值无】5.【字段名】输入大于【max】，给出提示不能大于max
             'field_name1': [''], 'field_type1': [''], 'enums1': ['无'], 'default_value1': [''], 'required1': [''], 
             'edit1': [''], 'max1': [''], 'remarks1': [''], 'case_level1': ['1']
            """
            field_name = request.POST.get(f'field_name{i}')
            field_type = request.POST.get(f'field_type{i}')
            field_required = request.POST.get(f'required{i}')
            field_min = request.POST.get(f'min{i}')
            field_digit_num = request.POST.get(f'digitNum{i}')
            if field_digit_num:
                field_digit_num = int(field_digit_num)
            if field_min:
                field_min = int(field_min)
            field_max = request.POST.get(f'max{i}')
            if field_max:
                field_max = int(field_max)
            display = request.POST.get(f"display{i}")
            field_default = request.POST.get(f'default_value{i}')
            case_1_pre_condition = f"已登录{case_system}"
            case_level = request.POST.get(f'case_level{i}')
            if case_level:
                case_level = int(case_level)
            # TODO case_level
            case_precondition = case_1_pre_condition
            case_enums = request.POST.get(f'enums{i}')
            if field_name:

                if field_type == "文本":
                    """
                        1. 文本：可输入字母和数字
                        2. 纯数字：只能输入数字
                    """
                    case_text_title = []
                    case_text_steps = []
                    case_text_expect_result = []
                    if field_min:
                        case_text_title += [
                            f"{field_name}输入{field_min + 1}个字符",
                            f"{field_name}输入{field_min - 1}个字符",
                            f"{field_name}输入{field_min}个字符",
                        ]
                        case_text_steps += [
                            f"1.进入{module}{page_name}页面；2.{field_name}输入{field_min + 1}个字符；",
                            f"1.进入{module}{page_name}页面；2.{field_name}输入超过{field_min - 1}个字符；",
                            f"1.进入{module}{page_name}页面；2.{field_name}输入{field_min}个字符；",
                        ]
                        case_text_expect_result += [
                            f"提示{field_name}不能超过{field_min}个字符",
                            f"保存后的数据与输入的数据一致",
                            f"保存后的数据与输入的数据一致",
                        ]
                    if field_max:
                        case_text_title += [
                            f"{field_name}输入{field_max + 1}个字符",
                            f"{field_name}输入{field_max - 1}个字符",
                            f"{field_name}输入{field_max}个字符",
                        ]
                        case_text_steps += [
                            f"1.进入{module}{page_name}页面；\n2.{field_name}输入{field_max + 1}个字符；",
                            f"1.进入{module}{page_name}页面；\n2.{field_name}输入超过{field_max - 1}个字符；",
                            f"1.进入{module}{page_name}页面；\n2.{field_name}输入{field_max}个字符；",
                        ]
                        case_text_expect_result += [
                            f"提示{field_name}不能超过{field_max}个字符",
                            f"保存后数据与输入数据一致",
                            f"保存后数据与输入数据一致",
                        ]
                    if field_min and field_max:
                        if field_min < field_max:
                            for _ in range(2):
                                num = random.randint(field_min, field_max)
                                case_text_title += [f'{field_name}输入{num}个字符']
                                case_text_steps += [
                                    f"1.进入{module}{page_name}页面；2.{field_name}输入{num}个字符；",
                                ]
                                case_text_expect_result += ["保存后的数据与输入的数据一致"]
                        else:
                            error_message = f"{field_name}的左边界值应小于右边界值"
                            return render(request, 'app01/newRowError.html', {"error_message": error_message})
                    case_text_title += [
                        f"{field_name}输入字符串中含空格",
                        f"{field_name}输入字符串首尾含空格",
                        f"{field_name}输入特殊字符",
                        f"{field_name}输入html格式字符",
                        f"{field_name}输入NULL或null字符串",
                        f"{field_name}输入普通字符串",
                    ]
                    case_text_steps += [
                        f"1.进入{module}{page_name}页面；2.{field_name}输入字符串中含空格；",
                        f"1.进入{module}{page_name}页面；2.{field_name}输入字符串首尾含空格；",
                        f"1.进入{module}{page_name}页面；2.{field_name}输入特殊字符，如~!@#$%^&*()_+|=-\\`[];’”:,./?<>；",
                        f"1.进入{module}{page_name}页面；2.{field_name}输入html格式字符,如<script>alert(/xss/)</script>；",
                        f"1.进入{module}{page_name}页面；2.{field_name}输入NULL或null字符串；",
                        f"1.进入{module}{page_name}页面；2.{field_name}输入普通字符串；",

                    ]
                    case_text_expect_result += [
                        "保存后的数据与输入的数据一致",
                        "自动过滤首尾空格，保存后的数据与输入的数据一致",
                        "保存后的数据与输入的数据一致",
                        "保存后的数据与输入的数据一致",
                        "保存后的数据与输入的数据一致",
                        "保存后的数据与输入的数据一致",
                    ]
                    for _ in range(len(case_text_title)):
                        case.create(
                            title=case_text_title[_], pre_condition=case_1_pre_condition, case_steps=case_text_steps[_],
                            case_level=case_level, creator=case_creator, expect_result=case_text_expect_result[_],
                            create_time=time.strftime("%Y-%m-%d %H:%M:%S"), remarks='', page='编辑', primary_module=primary_module,
                            project_id=project_id, sub_module=sub_module,
                        )
                elif field_type == '数字':
                    case_num1_title = []
                    case_num1_expect_result = []
                    case_num1_steps = []
                    case_num1_create_time = time.strftime('%Y-%m-%d %H:%M:%S')
                    if field_min:
                        case_num1_title += [
                            f'{field_name}输入{field_min - 1}',
                            f'{field_name}输入{field_min}',
                            f'{field_name}输入{field_min + 1}',
                        ]
                        case_num1_steps += [
                            f'1.进入{module}{page_name}页面；2.{field_name}输入{field_min - 1}；',
                            f'1.进入{module}{page_name}页面；2.{field_name}输入{field_min}；',
                            f'1.进入{module}{page_name}页面；2.{field_name}输入{field_min + 1}；',
                        ]
                        case_num1_expect_result += [
                            f"提示{field_name}不能小于{field_min}",
                            f"保存后的数据与输入的数据一致",
                            f"保存后的数据与输入的数据一致",
                        ]
                    if field_max:
                        case_num1_title += [
                            f'{field_name}输入{field_max + 1}',
                            f'{field_name}输入{field_max}',
                            f'{field_name}输入{field_max - 1}',
                        ]
                        case_num1_steps += [
                            f'1.进入{module}{page_name}页面；2.{field_name}输入{field_max + 1}；',
                            f'1.进入{module}{page_name}页面；2.{field_name}输入{field_max}；',
                            f'1.进入{module}{page_name}页面；2.{field_name}输入{field_max - 1}；',
                        ]
                        case_num1_expect_result += [
                            f"提示{field_name}不能大于{field_max}",
                            "保存后的数据与输入的数据一致",
                            "保存后的数据与输入的数据一致",
                        ]
                    if field_min and field_max:
                        if field_min < field_max:
                            random_list = []
                            for _ in range(3):
                                num = random.randint(field_min, field_max)
                                random_list.append(num)
                                case_num1_title += [f'{field_name}输入{num}']
                                case_num1_steps += [
                                    f'1.进入{module}{page_name}页面；2.{field_name}输入{num}；',
                                ]
                                case_num1_expect_result += ["保存后的数据与输入的数据一致"]
                        else:
                            error_message = f"{field_name}的左边界值应小于右边界值"
                            return render(request, 'app01/newRowError.html', {"error_message": error_message})

                    if field_digit_num:
                        case_num1_title += [
                            f'{field_name}输入{field_digit_num + 1}位数的值',
                            f'{field_name}输入{field_digit_num - 1}位数的值',
                            f'{field_name}输入{field_digit_num}位数的值',
                        ]
                        case_num1_steps += [
                            f'1.进入{module}{page_name}页面；2.{field_name}输入{field_digit_num + 1}位数的值；',
                            f'1.进入{module}{page_name}页面；2.{field_name}输入{field_digit_num}位数的值；',
                            f'1.进入{module}{page_name}页面；2.{field_name}输入{field_digit_num - 1}位数的值；',
                        ]
                        case_num1_expect_result += [
                            f'无法输入或给出错误提示,{field_name}的位数不能大于{field_digit_num}',
                            '保存后的数据与输入的数据一致，无错误提示',
                            '保存后的数据与输入的数据一致，无错误提示',
                        ]
                    for i in range(len(case_num1_title)):
                        case.create(
                            title=case_num1_title[i], pre_condition=case_1_pre_condition,
                            case_steps=case_num1_steps[i], primary_module=primary_module, sub_module=sub_module,
                            case_level=case_level, creator=case_creator,
                            expect_result=case_num1_expect_result[i],
                            create_time=case_num1_create_time, remarks='', page='编辑',
                            project_id=project_id
                        )
                elif field_type == '邮箱':
                    case_email_title = []
                    case_email_steps = []
                    case_email_expect_result = []
                    case_email_create_time = time.strftime('%Y-%m-%d %H:%M:%S')
                    if field_min:
                        case_email_title += [
                            f"{field_name}输入长度为{field_min - 1}的邮箱名",
                            f"{field_name}输入长度为{field_min}的邮箱名",
                            f"{field_name}输入长度为{field_min + 1}的邮箱名",
                        ]
                        case_email_steps += [
                            f'1.进入{module}{page_name}页面；2.{field_name}输入长度为{field_min - 1}的邮箱名；',
                            f'1.进入{module}{page_name}页面；2.{field_name}输入长度为{field_min}的邮箱名；',
                            f'1.进入{module}{page_name}页面；2.{field_name}输入长度为{field_min + 1}的邮箱名；',
                        ]
                        case_email_expect_result += [
                            f"提示邮箱名长度不能少于{field_min}位",
                            f'无错误提示',
                            f'无错误提示',
                        ]
                    if field_max:
                        case_email_title += [
                            f"{field_name}输入长度为{field_max - 1}的邮箱名",
                            f"{field_name}输入长度为{field_max}的邮箱名",
                            f"{field_name}输入长度为{field_max + 1}的邮箱名",
                        ]
                        case_email_steps += [
                            f'1.进入{module}{page_name}页面；2.{field_name}输入长度为{field_max - 1}的邮箱名；',
                            f'1.进入{module}{page_name}页面；2.{field_name}输入长度为{field_max}的邮箱名；',
                            f'1.进入{module}{page_name}页面；2.{field_name}输入长度为{field_max + 1}的邮箱名；',
                        ]
                        case_email_expect_result += [
                            f"无错误提示",
                            f'无错误提示',
                            f'提示邮箱名长度不能多于{field_max}位',
                        ]
                    if field_min and field_max:
                        if field_min < field_max:
                            random_list = []
                            for _ in range(1):
                                num = random.randint(field_min, field_max)
                                random_list.append(num)
                                case_email_title += [f'{field_name}输入长度为{num}的邮箱名']
                                case_email_steps += [
                                    f'1.进入{module}{page_name}页面；2.{field_name}长度为{num}的邮箱名；',
                                ]
                                case_email_expect_result += ["无错误提示"]
                        else:
                            error_message = f"{field_name}的左边界值应小于右边界值"
                            return render(request, 'app01/newRowError.html', {"error_message": error_message})
                    case_email_title += [
                        f'{field_name}输入无@的邮箱格式',
                        f'{field_name}输入@前无内容的邮箱格式',
                        f'{field_name}输入@后无内容的邮箱格式',
                        f'{field_name}输入正确的邮箱格式',

                    ]
                    case_email_steps += [
                        f'1.进入{module}{page_name}页面；2.{field_name}输入无@的邮箱格式，如ab.com',
                        f'1.进入{module}{page_name}页面；2.{field_name}输入@前无内容的邮箱格式，如@b.com',
                        f'1.进入{module}{page_name}页面；2.{field_name}输入@后无内容的邮箱格式，如a@.com',
                        f'1.进入{module}{page_name}页面；2.{field_name}输入@后无内容的邮箱格式，如zhangsan@126.com',
                    ]
                    case_email_expect_result += [
                        f'提示邮箱格式错误',
                        f'提示邮箱格式错误',
                        f'提示邮箱格式错误',
                        f'无错误提示',
                    ]
                    for _ in range(len(case_email_title)):
                        case.create(
                            title=case_email_title[_], pre_condition=case_1_pre_condition,
                            case_steps=case_email_steps[_], project_id=project_id,
                            case_level=case_level, creator=case_creator,
                            expect_result=case_email_expect_result[_],
                            primary_module=primary_module, sub_module=sub_module,
                            create_time=case_email_create_time, remarks='', page='编辑'
                        )
                elif field_type == '日期':
                    case_date_title = []
                    case_date_steps = []
                    case_date_expect_result = []
                    case_date_title += [
                        f'{field_name}月份输入小于等于0',
                        f'{field_name}月份输入大于等于13',
                        f'{field_name}月份输入大于0小于13',
                        f'{field_name}月份输入汉字',
                        f'{field_name}月份输入特殊字符',
                        f'{field_name}月份输入英文字符',
                        f'{field_name}日数，大月输入小于等于31的值',
                        f'{field_name}日数，小于输入小于等于30的值',
                        f'{field_name}日数，大月输入大于31的整数',
                        f'{field_name}日数，大月输入大于30的整数',
                        f'{field_name}日数，非闰年2月输入大于28的整数',
                        f'{field_name}日数，非闰年2月输入小于等于28的正整数',
                        f'{field_name}日数，闰年2月输入小于等于29的正整数',
                        f'{field_name}日数，闰年2月输入大于29的整数',
                        f'{field_name}日数输入汉字',
                        f'{field_name}日数输入特殊字符',
                        f'{field_name}日数输入英文字符',
                        f'{field_name}年份输入大于4位整数',
                        f'{field_name}年份输入小于4位整数',
                        f'{field_name}年份输入4位整数',
                        f'{field_name}年份输入汉字',
                        f'{field_name}年份输入特殊字符',
                        f'{field_name}年份输入英文字符',
                    ]
                    case_date_steps += [
                        f'1.进入{module}{page_name}页面；2.{field_name}月份输入-1',
                        f'1.进入{module}{page_name}页面；2.{field_name}月份输入13',
                        f'1.进入{module}{page_name}页面；2.{field_name}月份输入6',
                        f'1.进入{module}{page_name}页面；2.{field_name}月份输入测试',
                        f'1.进入{module}{page_name}页面；2.{field_name}月份输入特殊符合-!@#$%^&*().',
                        f'1.进入{module}{page_name}页面；2.{field_name}月份输入test',
                        f'1.进入{module}{page_name}页面；2.{field_name}月份输入1，日输入31',
                        f'1.进入{module}{page_name}页面；2.{field_name}月份输入4，日输入30',
                        f'1.进入{module}{page_name}页面；2.{field_name}月份输入1，日输入32',
                        f'1.进入{module}{page_name}页面；2.{field_name}月份输入4，日输入31',
                        f'1.进入{module}{page_name}页面；2.{field_name}年输入2022，月份输入2，日输入29',
                        f'1.进入{module}{page_name}页面；2.{field_name}年输入2022，月份输入2，日输入28',
                        f'1.进入{module}{page_name}页面；2.{field_name}年输入2020，月份输入2，日输入29',
                        f'1.进入{module}{page_name}页面；2.{field_name}年输入2020，月份输入2，日输入30',
                        f'1.进入{module}{page_name}页面；2.{field_name}日数输入测试',
                        f'1.进入{module}{page_name}页面；2.{field_name}日数输入特殊符合-!@#$%^&*().',
                        f'1.进入{module}{page_name}页面；2.{field_name}日数输入test',
                        f'1.进入{module}{page_name}页面；2.{field_name}年输入10000',
                        f'1.进入{module}{page_name}页面；2.{field_name}年输入100',
                        f'1.进入{module}{page_name}页面；2.{field_name}年输入2022',
                        f'1.进入{module}{page_name}页面；2.{field_name}年份输入测试',
                        f'1.进入{module}{page_name}页面；2.{field_name}年份输入特殊符合-!@#$%^&*().',
                        f'1.进入{module}{page_name}页面；2.{field_name}年份输入test',
                    ]
                    case_date_expect_result += [
                        f'小于等于0的月份自动更新为1或给出错误提示，{field_name}月份不能小于等于0',
                        f'大于等于13的月份自动更新为12或给出错误提示，{field_name}月份不能大于等于13',
                        f'保存后的数据与输入的数据一致，无错误提示',
                        f'汉字无法写入或给出错误提示，{field_name}月份为1-12的正整数',
                        f'特殊字符无法写入或给出错误提示，{field_name}月份为1-12的正整数',
                        f'英文字符无法写入或给出错误提示，{field_name}月份为1-12的正整数',
                        '保存后的数据与输入的数据一致，无错误提示',
                        '保存后的数据与输入的数据一致，无错误提示',
                        f'大月日数大于31自动更新为31或给出错误提示，{field_name}大月日数不能大于31',
                        f'小月日数大于30自动更新为30或给出错误提示，{field_name}小月日数不能大于30',
                        f'非闰年2月大于28的日数自动更新为28或给出错误提示，{field_name}非闰年2月日数不能大于28',
                        '保存后的数据与输入的数据一致，无错误提示',
                        '保存后的数据与输入的数据一致，无错误提示',
                        f'闰年2月大于29的日数自动更新为29或给出错误提示，{field_name}闰年2月日数不能大于29',
                        f'汉字无法写入或给出错误提示，{field_name}日数为正整数',
                        f'特殊字符无法写入或给出错误提示，{field_name}日数为正整数',
                        f'英文字符无法写入或给出错误提示，{field_name}日数为正整数',
                        f'无法输入或给出错误提示，{field_name}年份位数不能大于4',
                        f'自动在输入前补一位0或给出错误提示，{field_name}年份位数不能小于4',
                        '保存后的数据与输入的数据一致，无错误提示',
                        f'汉字无法写入或给出错误提示，{field_name}年份为位数为4的正整数',
                        f'特殊字符无法写入或给出错误提示，{field_name}年份为位数为4的正整数',
                        f'英文字符无法写入或给出错误提示，{field_name}年份为位数为4的正整数',
                    ]
                    for _ in range(len(case_date_title)):
                        case.create(
                            title=case_date_title[_], pre_condition=case_1_pre_condition,
                            case_steps=case_date_steps[_], primary_module=primary_module,sub_module=sub_module,
                            case_level=case_level, creator=case_creator,
                            expect_result=case_date_expect_result[_], project_id=project_id,
                            create_time=time.strftime("%Y-%m-%d %H:%M:%S"), remarks='', page='编辑'
                        )
                elif field_type == '时间':
                    case_time_title = []
                    case_time_steps = []
                    case_time_expect_result = []
                    case_time_title += [
                        f'{field_name}的时输入24',
                        f'{field_name}的时输入00',
                        f'{field_name}时输入汉字',
                        f'{field_name}时输入字母',
                        f'{field_name}时输入特殊符号',
                        f'{field_name}的分输入60',
                        f'{field_name}的分输入59',
                        f'{field_name}的分输入00',
                        f'{field_name}的分输入汉字',
                        f'{field_name}的分输入字母',
                        f'{field_name}的分输入特殊符号',
                        f'{field_name}的秒输入60',
                        f'{field_name}的秒输入59',
                        f'{field_name}的秒输入00',
                        f'{field_name}的秒输入汉字',
                        f'{field_name}的秒输入字母',
                        f'{field_name}的秒输入特殊符号',
                    ]
                    case_time_steps += [
                        f'1.进入{module}{page_name}页面；2.{field_name}的时输入24',
                        f'1.进入{module}{page_name}页面；2.{field_name}的时输入00',
                        f'1.进入{module}{page_name}页面；2.{field_name}的时输入测试',
                        f'1.进入{module}{page_name}页面；2.{field_name}的时输入test',
                        f'1.进入{module}{page_name}页面；2.{field_name}的时输入.*?!@#',
                        f'1.进入{module}{page_name}页面；2.{field_name}的分输入60',
                        f'1.进入{module}{page_name}页面；2.{field_name}的分输入59',
                        f'1.进入{module}{page_name}页面；2.{field_name}的分输入00',
                        f'1.进入{module}{page_name}页面；2.{field_name}的分输入测试',
                        f'1.进入{module}{page_name}页面；2.{field_name}的分输入test',
                        f'1.进入{module}{page_name}页面；2.{field_name}的分输入.*?!@#',
                        f'1.进入{module}{page_name}页面；2.{field_name}的秒输入60',
                        f'1.进入{module}{page_name}页面；2.{field_name}的秒输入59',
                        f'1.进入{module}{page_name}页面；2.{field_name}的秒输入00',
                        f'1.进入{module}{page_name}页面；2.{field_name}的秒输入测试',
                        f'1.进入{module}{page_name}页面；2.{field_name}的秒输入test',
                        f'1.进入{module}{page_name}页面；2.{field_name}的秒输入.*?!@#',

                    ]
                    case_time_expect_result += [
                        f"24自动转换为23或给出错误提示，时不能大于23",
                        f"正常保存",
                        f"无法输入或给出错误提示，时为0-23的整数",
                        f"无法输入或给出错误提示，时为0-23的整数",
                        f"无法输入或给出错误提示，时为0-23的整数",
                        f"60自动转换为59或给出错误提示，分不能大于59",
                        f"正常保存",
                        f"正常保存",
                        f"无法输入或给出错误提示，分为0-59的整数",
                        f"无法输入或给出错误提示，分为0-59的整数",
                        f"无法输入或给出错误提示，分为0-59的整数",
                        f"60自动转换为59或给出错误提示，秒不能大于59",
                        f"正常保存",
                        f"正常保存",
                        f"无法输入或给出错误提示，秒为0-59的整数",
                        f"无法输入或给出错误提示，秒为0-59的整数",
                        f"无法输入或给出错误提示，秒为0-59的整数",
                    ]
                    for _ in range(len(case_time_title)):
                        case.create(
                            title=case_time_title[_], pre_condition=case_1_pre_condition,
                            case_steps=case_time_steps[_],primary_module=primary_module,sub_module=sub_module,
                            case_level=case_level, creator=case_creator,
                            expect_result=case_time_expect_result[_],
                            create_time=time.strftime("%Y-%m-%d %H:%M:%S"), remarks='', page='编辑'
                        )
                elif field_type == '密码':
                    case_pwd_title = []
                    case_pwd_steps = []
                    case_pwd_expect_result = []
                    case_pwd_title += [
                        f'{field_name}输入的密码密文显示'
                    ]
                    case_pwd_steps += [
                        f'1.进入{module}{page_name}页面；2.{field_name}输入密码',

                    ]
                    case_pwd_expect_result += [
                        f'{field_name}密文显示',
                    ]
                    for _ in range(len(case_pwd_title)):
                        case.create(
                            title=case_pwd_title[_], pre_condition=case_1_pre_condition,
                            case_steps=case_pwd_steps[_],primary_module=primary_module,sub_module=sub_module,
                            case_level=case_level, creator=case_creator,
                            expect_result=case_pwd_expect_result[_], project_id=project_id,
                            create_time=time.strftime("%Y-%m-%d %H:%M:%S"), remarks='', page='编辑'
                        )
                elif field_type == '单选':
                    case_radio_title = []
                    case_radio_steps = []
                    case_radio_expect_result = []
                    case_radio_title += [
                        f"{field_name}同时选中多个",
                        f"{field_name}初始状态默认选中一个值",
                        f"{field_name}选项名和选项值检查",
                    ]
                    case_radio_steps += [
                        f"1.进入{module}{page_name}页面；2.对{field_name}进行同时选中多个选项的操作；",
                        f"1.进入{module}{page_name}页面；2.查看{field_name}初始状态是否默认选中一个值；",
                        f"1.进入{module}{page_name}页面；2.查看{field_name}的选项名和选项值是否符合设计要求",

                    ]
                    case_radio_expect_result += [
                        f"{field_name}同时只能选中一个选项",
                        f"{field_name}初始状态默认选中一个值，不能为空",
                        f"{field_name}的选项名和选项值符合设计要求",
                    ]
                    if case_enums:
                        try:
                            case_enums_list = case_enums.split(',')
                            for _ in case_enums_list:
                                case_radio_title += [f'{field_name}选中{_}，检查存入数据库的值']
                                case_radio_steps += [
                                    f"1.进入{module}{page_name}页面；2.{field_name}选中{_}；"
                                ]
                                case_radio_expect_result += [
                                    f'存入数据库的值与选项的值一致'
                                ]
                        except Exception as error1:
                            return render(request, 'app01/500_error.html', {'error_message': error1})
                    print("749**********", case_level)
                    print("749**********", type(case_level))
                    for _ in range(len(case_radio_title)):
                        case.create(
                            title=case_radio_title[_], pre_condition=case_1_pre_condition,
                            case_steps=case_radio_steps[_], project_id=project_id, primary_module=primary_module,
                            case_level=case_level, creator=case_creator,sub_module=sub_module,
                            expect_result=case_radio_expect_result[_],
                            create_time=time.strftime("%Y-%m-%d %H:%M:%S"), remarks='', page='编辑'
                        )
                elif field_type == '多选':
                    case_checkbox_title = []
                    case_checkbox_steps = []
                    case_checkbox_expect_result = []
                    case_checkbox_title += [
                        f'{field_name}同时选中多个选项',
                        f'{field_name}同时都不选中'
                    ]
                    case_checkbox_steps += [
                        f"1.进入{module}{page_name}页面；2.对{field_name}进行同时选中多个选项的操作；3.查看数据库存入的数据",
                        f"1.进入{module}{page_name}页面；2.{field_name}的选项都不选中",

                    ]
                    case_checkbox_expect_result += [
                        f'同时被选中的选项存储到数据库中正确',
                        f'根据需求给出提示',
                    ]
                    if case_enums:
                        try:
                            case_enums_list = case_enums.split(',')
                            for _ in case_enums_list:
                                case_checkbox_title += [f'{field_name}选中{_}，检查存入数据库的值']
                                case_checkbox_steps += [
                                    f"1.进入{module}{page_name}页面；2.{field_name}选中{_}；"
                                ]
                                case_checkbox_expect_result += [
                                    f'存入数据库的值与选项的值一致'
                                ]
                        except Exception as error1:
                            return render(request, 'app01/500_error.html', {'error_message': error1})
                    print("789**********", case_level)
                    print("789**********", type(case_level))
                    for _ in range(len(case_checkbox_title)):
                        case.create(
                            title=case_checkbox_title[_], pre_condition=case_1_pre_condition,
                            case_steps=case_checkbox_steps[_],
                            case_level=int(case_level), creator=case_creator, primary_module=primary_module,
                            sub_module=sub_module,expect_result=case_checkbox_expect_result[_], project_id=project_id,
                            create_time=time.strftime("%Y-%m-%d %H:%M:%S"), remarks='', page='编辑'
                        )
                if field_required == "是":
                    case_common_title += [
                        f"{field_name}字段输入英文空格",
                        f"{field_name}字段输入中文空格",
                    ]
                    case_common_steps += [
                        f"1.进入{module}{page_name}页面；2.{field_name}输入英文空格；3.其他输入正确。",
                        f"1.进入{module}{page_name}页面；2.{field_name}输入中文空格；3.其他输入正确。",
                    ]
                    case_common_expect_result += [
                        f"提示{field_name}不能为空",
                        f"提示{field_name}不能为空",
                    ]
                else:
                    case_common_title += [f"{field_name}字段输入英文空格",
                                          f"{field_name}字段输入中文空格",
                                          ]
                    case_common_steps += [
                        f"1.进入{module}{page_name}页面；2.{field_name}输入英文空格；3.其他输入正确。",
                        f"1.进入{module}{page_name}页面；2.{field_name}输入中文空格；3.其他输入正确。",
                    ]
                    case_common_expect_result += [
                        f"无错误提示"
                        f"无错误提示",
                    ]
                if display == "是":
                    case_common_title += [f"{field_name}在表格表头中展示"]
                    case_common_steps += [f"1.进入{module}{page_name}页面；2.查看{field_name}展示在表格表头"]
                    case_common_expect_result += [f"{field_name}在表格表头中展示"]
                else:
                    case_common_title += [f"{field_name}在表格表头中不展示"]
                    case_common_steps += [f"1.进入{module}{page_name}页面；2.查看{field_name}不展示在表格表头"]
                    case_common_expect_result += [f"{field_name}在表格表头中不展示"]
                if field_default:
                    case_common_title += [f"{field_name}默认值为{field_default}"]
                    case_common_steps += [f"1.进入{module}{page_name}页面；2.查看{field_name}的默认值为{field_default}"]
                    case_common_expect_result += [f"{field_name}默认值为{field_default}"]
                case_common_title += [f"{field_name}在{module}{page_name}页面可见"]
                case_common_steps += [f"进入{module}{page_name}页面, 查看{field_name}字段可见"]
                case_common_expect_result += [f"{field_name}在{module}{page_name}页面可见"]
        if is_ui_case_needed == '需要':
            case_common_title += [
                f"{module}{page_name}页面布局检查",
                f"{module}{page_name}页面设计风格检查",
                f"{module}{page_name}页面文字检查",
                f"{module}{page_name}页面输入框、按钮尺寸检查",
                f"{module}{page_name}页面不同分辨率显示情况检查",

            ]
            case_common_steps += [
                f"1.进入{module}{page_name}页面；2.检查页面的布局以及输入框和按钮是否对齐",
                f"1.进入{module}{page_name}页面；2.检查页面的设计风格是否与UI相符",
                f"1.进入{module}{page_name}页面；2.检查文字是否有错别字，描述是否简洁易懂",
                f"1.进入{module}{page_name}页面；2.检查输入框及按钮的长度和高度是否符合设计原型",
                f"1.进入{module}{page_name}页面；2.检查页面在不同分辨率的情况下程序显示是否正常",
            ]
            case_common_expect_result += [
                f'{module}{page_name}页面，布局合理，输入框和按钮对齐',
                f'{module}{page_name}页面，设计风格与UI相符',
                f'{module}{page_name}页面，无错别字，描述简洁易懂',
                f'{module}{page_name}页面，输入框及按钮的长度和高度符合设计要求',
                f'{module}{page_name}页面，不同分辨率的情况下程序显示正常',
            ]
        for _ in range(len(case_common_title)):
            case.create(
                title=case_common_title[_], pre_condition=case_precondition,
                case_steps=case_common_steps[_], project_id=project_id,
                case_level=1, creator=case_creator, primary_module=primary_module, sub_module=sub_module,
                expect_result=case_common_expect_result[_],
                create_time=time.strftime("%Y-%m-%d %H:%M:%S"), remarks='', page='编辑'
            )

    return redirect(reverse('app01:edit_page_new_row'))


def edit_page_export_excel(request):
    # 导出excel数据
    # 设置HTTPResponse的类型
    cases = Cases.objects.all().filter(page__exact='编辑')
    excel_postfix = time.strftime("%y%m%d%H%M%S")
    excel_name = f'filename=editPageCase_{excel_postfix}.xls'
    return export(excel_name, cases)


def delete_page_export_excel(request):
    # 导出excel数据
    # 设置HTTPResponse的类型
    cases = Cases.objects.all().filter(page__exact='删除')
    excel_postfix = time.strftime("%y%m%d%H%M%S")
    excel_name = f'filename=DeleteFunctionCase_{excel_postfix}.xls'
    return export(excel_name, cases)


def page_import_export_excel(request):
    # 导出excel数据
    # 设置HTTPResponse的类型
    cases = Cases.objects.all().filter(page__exact='导入')
    excel_postfix = time.strftime("%y%m%d%H%M%S")
    excel_name = f'filename=ImportFunctionCase_{excel_postfix}.xls'
    return export(excel_name, cases)


def export_page_export_excel(request):
    # 导出excel数据
    # 设置HTTPResponse的类型
    cases = Cases.objects.all().filter(page__exact='导出')
    excel_postfix = time.strftime("%y%m%d%H%M%S")
    excel_name = f'filename=ExportFunctionCase_{excel_postfix}.xls'
    return export(excel_name, cases)


def edit_page_search_result_export(request):
    referer = request.headers.get('Referer')
    params_list = referer.split('&')
    params_dict = {}
    params_list = params_list[1:]
    for param in params_list:
        (key, value) = param.split('=')
        params_dict[key] = value
    start_date = params_dict['start_date']
    end_date = params_dict['end_date']
    case_title = params_dict['case_title']
    case_title = unquote(case_title, 'utf-8').strip("+")
    case_title = case_title.strip()
    case_creator = params_dict['case_creator']
    case_creator = unquote(case_creator, 'utf-8').strip("+")
    case_creator = case_creator.strip()
    if start_date and end_date:
        search_result = Cases.objects.filter(Q(create_time__gte=start_date + " 00:00:00") &
                                             Q(create_time__lte=end_date + " 23:59:59"),
                                             title__contains=case_title,
                                             creator__contains=case_creator,
                                             page__exact='编辑').order_by('-id')
    elif start_date:
        search_result = Cases.objects.filter(create_time__gte=start_date + " 00:00:00",
                                             title__contains=case_title,
                                             creator__contains=case_creator,
                                             page__exact='编辑').order_by('-id')
    elif end_date:
        search_result = Cases.objects.filter(create_time__lte=end_date + " 23:59:59",
                                             title__contains=case_title,
                                             creator__contains=case_creator,
                                             page__exact='编辑').order_by('-id')
    else:
        search_result = Cases.objects.filter(title__contains=case_title,
                                             creator__contains=case_creator,
                                             page__exact='编辑').order_by('-id')
    print(type(search_result))
    excel_postfix = time.strftime("%y%m%d%H%M%S")
    excel_name = f'filename=editPageCase_{excel_postfix}.xls'
    return export(excel_name, search_result)


def search_page(request):
    cases = Cases.objects.all().filter(page='查询').order_by("-id")
    p = request.GET.get('current_page', 1)
    p = int(p)
    paginator = Paginator(cases, 10)
    projects = Project.objects.all()
    users = User.objects.all()
    page_range = transfer_the_page_range(p, paginator)
    if paginator.num_pages - p > 5:
        last_page = True
    try:
        pages = paginator.page(p)
    except PageNotAnInteger:
        pages = paginator.page(1)
    except EmptyPage:
        pages = paginator.page(paginator.num_pages)
    return render(request, 'app01/search_page.html', locals())


def search_page_create_case(request):
    if request.method == 'POST':
        case_title = request.POST.get('case_title')
        pre_condition = request.POST.get('pre_condition')
        case_steps = request.POST.get('case_steps')
        creator = request.POST.get('creator')
        # TODO 修改模板文件
        expect_result = request.POST.get('expect_result')
        primary_module = request.POST.get('primary_module')
        sub_module = request.POST.get('sub_module')
        remarks = request.POST.get('remarks')
        create_time = time.strftime('%Y-%m-%d %H:%M:%S')
        level = request.POST.get('level')
        level = int(level)
        case = Cases.objects.all()
        case_system = request.POST.get("project_name", '')

        project = Project.objects.get(project_name=case_system)
        project_id = project.id
        case.create(
            title=case_title, pre_condition=pre_condition, case_steps=case_steps, case_level=level,
            project_id=project_id, primary_module=primary_module, sub_module=sub_module,
            creator=creator, expect_result=expect_result, create_time=create_time, remarks=remarks, page='查询'
        )
        return redirect(reverse('app01:search_page'))


def search_page_search_case(request):
    try:
        if request.method == 'GET':
            start_date = request.GET.get("start_date", '')
            end_date = request.GET.get("end_date", '')
            case_title = request.GET.get('case_title', '')
            case_title = case_title.strip()
            case_creator = request.GET.get('case_creator', '')
            case_creator = case_creator.strip()
            if start_date and end_date:
                search_result = Cases.objects.filter(Q(create_time__gte=start_date + " 00:00:00") &
                                                     Q(create_time__lte=end_date + " 23:59:59"),
                                                     title__contains=case_title, page='查询',
                                                     creator__contains=case_creator).order_by('-id')
            elif start_date:
                search_result = Cases.objects.filter(create_time__gte=start_date + " 00:00:00",
                                                     title__contains=case_title, page='查询',
                                                     creator__contains=case_creator).order_by('-id')
            elif end_date:
                search_result = Cases.objects.filter(create_time__lte=end_date + " 23:59:59",
                                                     title__contains=case_title, page='查询',
                                                     creator__contains=case_creator).order_by('-id')
            else:
                search_result = Cases.objects.filter(title__contains=case_title, page='查询',
                                                     creator__contains=case_creator).order_by('-id')
            p = request.GET.get('current_page', 1)
            p = int(p)
            paginator = Paginator(search_result, 10)
            page_range = transfer_the_page_range(p, paginator)
            if paginator.num_pages - p > 5:
                last_page = True
            try:
                pages = paginator.page(p)
            except PageNotAnInteger:
                pages = paginator.page(1)
            except EmptyPage:
                pages = paginator.page(paginator.num_pages)
            return render(request, 'app01/search_page_search.html', locals())
    except ValidationError as error1:
        return render(request, 'app01/500_error.html', {"error_message": "年份不能超过4位数"})


def search_page_edit_case(request):
    return HttpResponse("search_page_edit_case")


def search_page_generate_case(request):
    if request.method == 'POST':
        case = Cases.objects.all()
        case_common_title = []
        case_common_steps = []
        case_common_expect_result = []
        total_len = len(request.POST)
        case_system = request.POST.get('auth')
        case_module = ''
        primary_module = request.POST.get("module1")
        sub_module = []
        for _ in range(2, 4):
            if request.POST.get(f"module{_}"):
                sub_module.append(request.POST.get(f"module{_}"))
        sub_module = ">>".join(sub_module)
        case_precondition = f'已登录{case_module}系统'
        page_name = request.POST.get('page_name')
        check_result_method = request.POST.get("check_result_method")
        case_creator = request.POST.get('creator')
        ui_case_needed = request.POST.get('ui_case')
        field_count = (total_len - 10) // 7
        project = Project.objects.get(project_name=case_system)
        project_id = project.id
        if field_count > 1:
            # case_combine_search_title = []
            case_combine_search_steps = []
            # case_combine_search_expect_result = []
            params = []
            field_name_list = []
            for i in range(field_count):
                field_name = request.POST.get(f'field_name{i}')
                field_type = request.POST.get(f'field_type{i}')
                enums = request.POST.get(f'enums{i}')
                symbol_date = request.POST.get(f'symbol_date{i}')
                date_ = request.POST.get(f'date{i}')
                symbol_time = request.POST.get(f'symbol_time{i}')
                time_ = request.POST.get(f'time{i}')
                time_ = str(time_).replace('T', ' ')
                field_name_list.append(field_name)
                case_single_condition_title = []
                case_single_condition_steps = []
                case_single_condition_expect_results = []
                if field_type in ["文本", "单选", "数字"]:
                    if not enums:
                        return HttpResponse(f"{field_name}的值不能为空")
                    else:
                        enums_list = enums.split(',')
                        params.append(enums_list)
                    title = f"根据{field_name}单一条件查询"
                    case_single_condition_title += [title]
                    if field_type == '文本':
                        """
                        1.输入的查询条件为数据库中存在的数据，看是否能正确地查出相应的数据
                        2.输入正确的查询条件，在前面加上空格，看是否能正确地查出相应的数据
                        3.输入数据库中不存在的数据
                        """
                        titles = [
                            f"【单一条件查询】查询条件{field_name}两端输入空格",
                            f"【单一条件查询】查询条件{field_name}精确查询",
                            f"【单一条件查询】查询条件{field_name}模糊查询",
                            f"【单一条件查询】查询条件{field_name}输入英文'符号",
                            f"【单一条件查询】查询条件{field_name}输入其他容易引起报错的特殊符号",
                        ]
                        steps = [
                            f"1.进入{page_name}页面；2.在查询条件{field_name}输入列表中存在的数据，并在两端加入一个或多个空格；3.其他查询条件保持默认；4.点击查询",
                            f"1.进入{page_name}页面；2.在查询条件{field_name}输入列表中存在的完整数据；3.其他查询条件保持默认；4.点击查询",
                            f"1.进入{page_name}页面；2.在查询条件{field_name}输入列表中存在的数据的部分内容；3.其他查询条件保持默认；4.点击查询",
                            f"1.进入{page_name}页面；2.在查询条件{field_name}输入英文单引号'；3.其他查询条件保持默认；4.点击查询",
                            f"1.进入{page_name}页面；2.在查询条件{field_name}输入英文单引号\\、<或%符号；3.其他查询条件保持默认；4.点击查询",
                        ]
                        expect_results = [
                            "依据需求文档对前后空格进行处理，查询结果正确无误",
                            "查询结果正确无误",
                            "查询结果正确无误",
                            "查询应不会报错，否则有很大可能存在SQL注入的漏洞",
                            "查询应不会报错",
                        ]
                        if enums_list:
                            for i1 in range(len(enums_list)):
                                titles.append(f'【单一条件查询】查询条件{field_name}输入{enums_list[i1]}')
                                steps.append(f"1.进入{page_name}页面；2.在查询条件{field_name}输入{enums_list[i1]}；3.其他查询条件保持默认；4.点击查询")
                                expect_results.append("查询结果正确无误")
                        case_single_condition_title += titles
                        case_single_condition_steps += steps
                        case_single_condition_expect_results += expect_results
                    elif field_type == '单选':
                        titles = []
                        steps = []
                        expect_results = []
                        if not enums:
                            return HttpResponse(f"{field_name}的值不能为空")
                        else:
                            enums_list = enums.split(',')
                            params.append(enums_list)
                        if enums_list:
                            for i1 in range(len(enums_list)):
                                titles.append(f'【单一条件查询】查询条件{field_name}输入{enums_list[i1]}')
                                steps.append(f"1.进入{page_name}页面；2.在查询条件{field_name}输入{enums_list[i1]}；3.其他查询条件保持默认；4.点击查询")
                                expect_results.append("查询结果正确无误")
                            case_single_condition_title += titles
                            case_single_condition_steps += steps
                            case_single_condition_expect_results += expect_results

                elif field_type == '多选':
                    # TODO 需要实现
                    titles = []
                    steps = []
                    expect_results = []
                    if not enums:
                        return HttpResponse(f"{field_name}的值不能为空")
                    else:
                        enums_multi_choice_list = enums.split(',')
                        enums_list = []
                        if len(enums_multi_choice_list) > 2:
                            new_list1 = deal_with_multi_options(enums_list)
                            if new_list1 < 10:
                                pass
                            else:
                                new_list1 = new_list1[:10]
                            params.append(new_list1)
                            generate_search_case_1(new_list1, titles, steps, expect_results, field_name, page_name)
                    if enums_list:
                        if len(enums_list) > 5:
                            new_list = deal_with_multi_for_single(enums_list)
                            if new_list < 10:
                                pass
                            else:
                                new_list = new_list[:10]
                            generate_search_case_1(new_list, titles, steps, expect_results, field_name, page_name)
                        else:
                            generate_search_case_1(enums_list, titles, steps, expect_results, field_name, page_name)
                    titles.append(f'【单一条件查询】查询条件{field_name}选中全部选项')
                    steps.append(
                        f"1.进入{page_name}页面；2.在查询条件{field_name}选中全部选项；3.其他查询条件保持默认；4.点击查询")
                    expect_results.append("查询结果正确无误")
                    case_single_condition_title += titles
                    case_single_condition_steps += steps
                    case_single_condition_expect_results += expect_results
                elif field_type == '日期':
                    if not date_:
                        return HttpResponse(f"{field_name}的值不能为空，请返回选定日期")
                    else:
                        date_list = [date_]  # 用于组合查询
                        # 以下为单一条件查询
                        titles = [
                            f"【单一条件查询】查询{field_name}{symbol_date}{date_}的数据",
                        ]
                        steps = [
                            f"1.进入{page_name}页面；2.在查询条件{field_name}选定日期{date_}；3.其他查询条件保持默认；4.点击查询",
                        ]
                        expect_results = [
                            "查询到所有满足条件的数据",
                        ]
                        case_single_condition_title += titles
                        case_single_condition_steps += steps
                        case_single_condition_expect_results += expect_results
                    params.append(date_list)
                elif field_type == '时间':
                    if not time_:
                        return HttpResponse(f"{field_name}的值不能为空")
                    else:
                        time_list = [time_]
                        # 以下为单一条件查询
                        titles = [
                            f"【单一条件查询】查询{field_name}{symbol_time}{date_}的数据",
                        ]
                        steps = [
                            f"1.进入{page_name}页面；2.在查询条件{field_name}选定时间{time_}；3.其他查询条件保持默认；4.点击查询",
                        ]
                        expect_results = [
                            "查询到满足时间条件的所有数据",
                        ]
                        case_single_condition_title += titles
                        case_single_condition_steps += steps
                        case_single_condition_expect_results += expect_results
                    params.append(time_list)
                for _ in range(len(case_single_condition_steps)):
                    case.create(
                        title=case_single_condition_title[_], pre_condition=case_precondition,
                        case_steps=case_single_condition_steps[_],
                        case_level=1, creator=case_creator, primary_module=primary_module, sub_module=sub_module,
                        expect_result=case_single_condition_expect_results[_],project_id=project_id,
                        create_time=time.strftime("%Y-%m-%d %H:%M:%S"), remarks='', page='查询'
                    )
            param_list = pare_wise(params)
            nv_list = []
            for param in param_list:
                filed_name_and_value = zip(field_name_list, param)
                nv_dict = dict((name, value) for name, value in filed_name_and_value)
                nv_list.append(nv_dict)
            for nv in nv_list:
                case_steps0 = "查询条件"
                n = 0
                for k, v in nv.items():
                    nv_len = len(nv)
                    if n == nv_len - 1:
                        case_steps0 += f"[{k}]输入[{v}]"
                    else:
                        case_steps0 += f"[{k}]输入[{v}]、"
                    n += 1
                case_combine_search_steps += [case_steps0]
            print(case_combine_search_steps)
            for _ in range(len(case_combine_search_steps)):
                if page_name:
                    case.create(
                        title=f"组合查询{_ + 1}", pre_condition=f"进入{page_name}页面", case_steps=case_combine_search_steps[_],
                        case_level=1, creator=case_creator, expect_result="正确执行查询动作,且查询结果正确",
                        create_time=time.strftime("%Y-%m-%d %H:%M:%S"), primary_module=primary_module,
                        sub_module=sub_module,remarks='', page='查询', project_id=project_id,
                    )
                else:
                    case.create(
                        title=f"组合查询{_ + 1}", pre_condition=f"已登录{case_system}", case_steps=case_combine_search_steps[_],
                        case_level=1, creator=case_creator, expect_result="正确执行查询动作,且查询结果正确",
                        create_time=time.strftime("%Y-%m-%d %H:%M:%S"), primary_module=primary_module,
                        sub_module=sub_module, remarks='', page='查询', project_id=project_id,
                    )
        else:
            print("nothing to say")

        case_ui_title = []
        case_ui_steps = []
        case_ui_expect_result = []

        # 查询功能通用测试用例
        if ui_case_needed:
            case_ui_title += [
                '查看UI是否显示正确，布局是否合理',

            ]
            case_ui_steps += [
                f'进入{page_name}页面，查看UI布局',
            ]
            case_ui_expect_result += [
                'UI显示正确，布局合理',
            ]
        case_common1_title = []
        case_common1_steps = []
        case_common1_expect_result = []
        case_common1_title += ["全部条件保持默认查询",
                               "执行查询操作后,查询条件应能保留",
                               "检查查询结果列表，每页显示记录条数正确、文字折行显示正确、页面布局美观",
                               "测试在查询条件下是否可以进行其它操作－例如修改删除等",
                               "检查查询是否区分大小写",

                               ]
        case_common1_steps += [
            f"进入{page_name}页面，依据默认查询条件，点击查询按钮",
            f"1.进入{page_name}页面，所有查询条件均输入任意值，点击查询按钮;2.查询后查询条件的值应保留",
            f"1.进入{page_name}页面，所有查询条件均输入任意值，点击查询按钮;2.检查查询结果列表，每页显示记录条数正确、文字折行显示正确、页面布局美观",
            f"1.进入{page_name}页面，输入可获取数据的查询条件，点击查询按钮;2.查询后对数据进行修改或删除，应能正常操作",
            f"1.进入{page_name}页面，针对数据有英文字符的记录，在对应条件输入全大写或全小写字符;2.点击查询，查看是否均能得到结果",
        ]
        case_common1_expect_result += [
            f"查询出全部数据",
            f"查询操作正常，查询条件的值保留",
            f"查询结果列表，每页显示记录条数正确、文字折行显示正确、页面布局美观",
            f"查询结果页面，可对数据进行正常的修改删除等操作",
            f"根据需求查看关键字是否区分大小写",
        ]
        for _ in range(len(case_common1_title)):
            case.create(
                title=case_common1_title[_], pre_condition=case_precondition,
                case_steps=case_common1_steps[_],  primary_module=primary_module, sub_module=sub_module,
                case_level=1, creator=case_creator,
                expect_result=case_common1_expect_result[_], project_id=project_id,
                create_time=time.strftime("%Y-%m-%d %H:%M:%S"), remarks='', page='查询'
            )

    return redirect('app01:search_page_new_row')


def page_import(request):
    cases = Cases.objects.all().filter(page='导入').order_by("-id")
    p = request.GET.get('current_page', 1)
    p = int(p)
    projects = Project.objects.all()
    users = User.objects.all()
    paginator = Paginator(cases, 10)
    page_range = transfer_the_page_range(p, paginator)
    if paginator.num_pages - p > 5:
        last_page = True
    try:
        pages = paginator.page(p)
    except PageNotAnInteger:
        pages = paginator.page(1)
    except EmptyPage:
        pages = paginator.page(paginator.num_pages)
    return render(request, 'app01/page_import.html', locals())


def page_import_create_case(request):
    if request.method == 'POST':
        case_title = request.POST.get('case_title')
        pre_condition = request.POST.get('pre_condition')
        case_steps = request.POST.get('case_steps')
        primary_module = request.POST.get('primary_module')
        sub_module = request.POST.get('sub_module')
        creator = request.POST.get('creator')
        expect_result = request.POST.get('expect_result')
        remarks = request.POST.get('remarks')
        create_time = time.strftime('%Y-%m-%d %H:%M:%S')
        level = request.POST.get('level')
        level = int(level)
        case = Cases.objects.all()
        case.create(
            title=case_title, pre_condition=pre_condition, case_steps=case_steps, case_level=level,
            creator=creator, expect_result=expect_result, create_time=create_time, remarks=remarks, page='导入',
            primary_module=primary_module, sub_module=sub_module,
        )
        return redirect(reverse('app01:page_import'))


def page_import_search_case(request):
    return HttpResponse("page_import_search_case")


def page_import_edit_case(request):
    return HttpResponse("page_import_edit_case")


def page_import_generate_case(request):
    """

    """
    if request.method == 'POST':
        case = Cases.objects.all()
        module = ""
        is_ui_case_needed = request.POST.get('ui_case')
        case_creator = request.POST.get("creator")
        case_system = request.POST.get("auth")
        primary_module = request.POST.get('module1')
        sub_module = []
        for _ in range(2, 5):
            if request.POST.get(f"module{_}"):
                sub_module.append(request.POST.get(f"module{_}"))
        sub_module = ">>".join(sub_module)
        for i in range(1, 5):
            dict_key = f'module{i}'

            if dict_key in request.POST:
                if request.POST.get(dict_key):
                    module += request.POST.get(dict_key) + ">>"
            else:
                break
        import_button_name = request.POST.get('import_button_name0')  # 导入按钮名称
        import_object = request.POST.get('import_object0')  # 导入对象
        file_type = request.POST.get('format0')  # 导入文件格式
        has_template0 = request.POST.get('has_template0')  # 是否有模板
        total_delete = request.POST.get('total_delete0')  # 彻底删除
        same_file0 = request.POST.get('same_file0')  # 相同文件
        same_name0 = request.POST.get('same_name0')  # 相同文件
        is_multi_import0 = request.POST.get('is_multi_import0')  # 是否支持批量导入，是，否
        check_result_method0 = request.POST.get('check_result_method0')  # 查看结果方式，是，否
        case_level = request.POST.get('case_level0')
        case_precondition = f"已登录{case_system}"
        case_title = []
        case_steps = []
        case_expect_result = []
        case_title += ["检查页面元素"]
        case_steps += [""]
    return HttpResponse("page_import_generate_case")


def export_page(request):
    cases = Cases.objects.all().filter(page='导出').order_by("-id")
    p = request.GET.get('current_page', 1)
    paginator = Paginator(cases, 10)
    p = int(p)
    projects = Project.objects.all()
    users = User.objects.all()
    page_range = transfer_the_page_range(p, paginator)
    if paginator.num_pages - p > 5:
        last_page = True
    try:
        pages = paginator.page(p)
    except PageNotAnInteger:
        pages = paginator.page(1)
    except EmptyPage:
        pages = paginator.page(paginator.num_pages)
    return render(request, 'app01/export_page.html', locals())


def export_page_create_case(request):
    if request.method == 'POST':
        case_title = request.POST.get('case_title')
        pre_condition = request.POST.get('pre_condition')
        primary_module = request.POST.get("primary_module")
        sub_module = request.POST.get("sub_module")
        case_steps = request.POST.get('case_steps')
        creator = request.POST.get('creator')
        expect_result = request.POST.get('expect_result')
        remarks = request.POST.get('remarks')
        create_time = time.strftime('%Y-%m-%d %H:%M:%S')
        level = request.POST.get('level')
        level = int(level)
        case = Cases.objects.all()
        case.create(
            title=case_title, pre_condition=pre_condition, case_steps=case_steps, case_level=level,
            creator=creator, expect_result=expect_result, create_time=create_time, remarks=remarks, page='导出',
            primary_module=primary_module, sub_module=sub_module,
        )
        return redirect(reverse('app01:export_page'))


def export_page_search_case(request):
    try:
        if request.method == 'GET':
            start_date = request.GET.get("start_date", '')
            end_date = request.GET.get("end_date", '')
            case_title = request.GET.get('case_title', '')
            case_title = case_title.strip()
            case_creator = request.GET.get('case_creator', '')
            case_creator = case_creator.strip()
            if start_date and end_date:
                search_result = Cases.objects.filter(Q(create_time__gte=start_date + " 00:00:00") &
                                                     Q(create_time__lte=end_date + " 23:59:59"),
                                                     title__contains=case_title, page='导出',
                                                     creator__contains=case_creator).order_by('-id')
            elif start_date:
                search_result = Cases.objects.filter(create_time__gte=start_date + " 00:00:00",
                                                     title__contains=case_title, page='导出',
                                                     creator__contains=case_creator).order_by('-id')
            elif end_date:
                search_result = Cases.objects.filter(create_time__lte=end_date + " 23:59:59",
                                                     title__contains=case_title, page='导出',
                                                     creator__contains=case_creator).order_by('-id')
            else:
                search_result = Cases.objects.filter(title__contains=case_title, page='导出',
                                                     creator__contains=case_creator).order_by('-id')
            p = request.GET.get('current_page', 1)
            p = int(p)
            paginator = Paginator(search_result, 10)
            page_range = transfer_the_page_range(p, paginator)
            if paginator.num_pages - p > 5:
                last_page = True
            try:
                pages = paginator.page(p)
            except PageNotAnInteger:
                pages = paginator.page(1)
            except EmptyPage:
                pages = paginator.page(paginator.num_pages)
            return render(request, 'app01/export_page_search.html', locals())
    except ValidationError as error1:
        return render(request, 'app01/500_error.html', {"error_message": "年份不能超过4位数"})


def export_page_edit_case(request):
    # TODO 导出功能用例编辑
    if request.method == 'POST':
        referer = request.headers.get('Referer')
        case_id = request.POST.get('case_id')
        case_id = int(case_id)
        case_title = request.POST.get('case_title')
        pre_condition = request.POST.get('pre_condition')
        case_steps = request.POST.get('case_steps')
        creator = request.POST.get('creator')
        primary_module = request.POST.get("primary_module")
        sub_module = request.POST.get("sub_module")
        project_name = request.POST.get('project_name')
        create_time = request.POST.get('create_time')
        level = request.POST.get('level')
        level = int(level)
        expect_result = request.POST.get('expect_result')
        real_result = request.POST.get('real_result')
        remarks = request.POST.get('remarks')
        case = Cases.objects.filter(id=case_id)
        try:

            project_id = Project.objects.get(project_name__exact=project_name).id
            case.update(
                title=case_title, pre_condition=pre_condition, case_steps=case_steps, case_level=level,
                creator=creator, expect_result=expect_result, create_time=create_time, remarks=remarks, page='导出',
                project_id=project_id, real_result=real_result, primary_module=primary_module, sub_module=sub_module,
            )
            return redirect(referer)
        except Exception as error1:
            print(error1)
            return HttpResponse("项目名称不存在，已修改后再次提交！")


def export_page_generate_case(request):
    return HttpResponse("export_page_generate_case")


def delete_page(request):
    cases = Cases.objects.all().filter(page='删除').order_by("-id")
    p = request.GET.get('current_page', 1)
    p = int(p)
    paginator = Paginator(cases, 10)
    page_range = transfer_the_page_range(p, paginator)
    projects = Project.objects.all()
    users = User.objects.all()
    if paginator.num_pages - p > 5:
        last_page = True
    try:
        pages = paginator.page(p)
    except PageNotAnInteger:
        pages = paginator.page(1)
    except EmptyPage:
        pages = paginator.page(paginator.num_pages)
    return render(request, 'app01/delete_page.html', locals())


def delete_page_create_case(request):
    if request.method == 'POST':
        referer = request.headers.get('Referer')
        case_title = request.POST.get('case_title')
        pre_condition = request.POST.get('pre_condition')
        primary_module = request.POST.get("primary_module")
        sub_module = request.POST.get("sub_module")
        case_steps = request.POST.get('case_steps')
        creator = request.POST.get('creator')
        expect_result = request.POST.get('expect_result')
        remarks = request.POST.get('remarks')
        create_time = time.strftime('%Y-%m-%d %H:%M:%S')
        project_name = request.POST.get('project_name')
        project = Project.objects.get(project_name__exact=project_name)
        level = request.POST.get('level')
        level = int(level)
        case = Cases.objects.all()
        case.create(
            title=case_title, pre_condition=pre_condition, case_steps=case_steps, case_level=level,
            creator=creator, expect_result=expect_result, create_time=create_time, remarks=remarks, page='删除',
            project_id=project.id, primary_module=primary_module, sub_module=sub_module,
        )
        return redirect(referer)


def delete_page_search_case(request):
    try:
        if request.method == 'GET':
            start_date = request.GET.get("start_date", '')
            end_date = request.GET.get("end_date", '')
            case_title = request.GET.get('case_title', '')
            case_title = case_title.strip()
            case_creator = request.GET.get('case_creator', '')
            case_creator = case_creator.strip()
            if start_date and end_date:
                search_result = Cases.objects.filter(Q(create_time__gte=start_date + " 00:00:00") &
                                                     Q(create_time__lte=end_date + " 23:59:59"),
                                                     title__contains=case_title, page='删除',
                                                     creator__contains=case_creator).order_by('-id')
            elif start_date:
                search_result = Cases.objects.filter(create_time__gte=start_date + " 00:00:00",
                                                     title__contains=case_title, page='删除',
                                                     creator__contains=case_creator).order_by('-id')
            elif end_date:
                search_result = Cases.objects.filter(create_time__lte=end_date + " 23:59:59",
                                                     title__contains=case_title, page='删除',
                                                     creator__contains=case_creator).order_by('-id')
            else:
                search_result = Cases.objects.filter(title__contains=case_title, page='删除',
                                                     creator__contains=case_creator).order_by('-id')
            p = request.GET.get('current_page', 1)
            p = int(p)
            paginator = Paginator(search_result, 10)
            page_range = transfer_the_page_range(p, paginator)
            if paginator.num_pages - p > 5:
                last_page = True
            try:
                pages = paginator.page(p)
            except PageNotAnInteger:
                pages = paginator.page(1)
            except EmptyPage:
                pages = paginator.page(paginator.num_pages)
            return render(request, 'app01/search_page_search.html', locals())
    except ValidationError as error1:
        return render(request, 'app01/500_error.html', {"error_message": "年份不能超过4位数"})


def delete_page_edit_case(request):
    if request.method == 'POST':
        referer = request.headers.get('Referer')
        case_id = request.POST.get('case_id')
        case_id = int(case_id)
        case_title = request.POST.get('case_title')
        pre_condition = request.POST.get('pre_condition')
        case_steps = request.POST.get('case_steps')
        creator = request.POST.get('creator')
        primary_module = request.POST.get("primary_module")
        sub_module = request.POST.get("sub_module")
        project_name = request.POST.get('project_name')
        create_time = request.POST.get('create_time')
        level = request.POST.get('level')
        level = int(level)
        expect_result = request.POST.get('expect_result')
        real_result = request.POST.get('real_result')
        remarks = request.POST.get('remarks')
        case = Cases.objects.filter(id=case_id)
        try:

            project_id = Project.objects.get(project_name__exact=project_name).id
            case.update(
                title=case_title, pre_condition=pre_condition, case_steps=case_steps, case_level=level,
                creator=creator, expect_result=expect_result, create_time=create_time, remarks=remarks, page='删除',
                project_id=project_id, real_result=real_result, primary_module = primary_module, sub_module = sub_module,
            )
            return redirect(referer)
        except Exception as error1:
            print(error1)
            return HttpResponse("项目名称不存在，已修改后再次提交！")


def delete_page_generate_case(request):
    """
        F_001        	删除按钮	正常弹出删除确认提示框。
        F_002        	删除提示信息	根据提示信息：点击【否】，不进行任何操作，回到原界面；
                        点击【是】删除，界面刷新不显示此条数据，停留在所删除记录所在页，总记录数-1。
　
        F_003        	删除边界值是否正常	界面正常刷新至上一页，页数等于原页数-1。
        F_004        	删除特殊状态下的信息时，是否给予明确的提示信息	给予明确提示信息，不允许删除。
    """
    if request.method == 'POST':
        case = Cases.objects.all()
        module = ""
        is_ui_case_needed = request.POST.get('ui_case')
        case_creator = request.POST.get("creator")
        case_system = request.POST.get("auth")
        primary_module = None
        sub_module = []
        for i in range(1, 100):
            dict_key = f'module{i}'
            if dict_key in request.POST:
                if dict_key == 'module1':
                    primary_module = request.POST.get(dict_key)
                else:
                    if request.POST.get(dict_key):
                        sub_module.append(request.POST.get(dict_key))
                if request.POST.get(dict_key):
                    module += request.POST.get(dict_key) + ">>"
            else:
                break
        print("---------------------------", sub_module)
        if sub_module:
            sub_module = ">>".join(sub_module)
        print("***************************", sub_module)
        delete_button_name = request.POST.get('delete_button_name0')
        delete_object = request.POST.get('delete_object0')  # 删除对象
        need_check = request.POST.get('need_check0')  # 需勾选
        multi_delete = request.POST.get('multi_delete0')  # 批量删除
        total_delete = request.POST.get('total_delete0')  # 彻底删除
        check_result_method = request.POST.get('check_result_method0')  # 检查结果
        page_name = request.POST.get('page_name')
        multi_delete_button_name = request.POST.get('multi_delete_button_name0')
        case_level = request.POST.get('case_level0')
        case_precondition = f"已登录{case_system}"
        case_title = []
        case_steps = []
        case_expect_result = []
        if delete_button_name:
            if is_ui_case_needed:
                case_title += [

                ]
            if need_check == '是':
                case_title += [
                    f"不勾选{delete_object}记录,点击{delete_button_name}",
                    f"勾选一条{delete_object}记录,点击{delete_button_name}，确认删除",
                    f"勾选一条{delete_object}记录,点击{delete_button_name}，取消删除",
                    f"勾选多条{delete_object}记录,点击{delete_button_name}",
                ]
                case_steps += [
                    f"1.进入{module}{page_name}页面页面；2.不勾选{delete_object}记录,点击{delete_button_name}",
                    f"1.进入{module}{page_name}页面页面；2.勾选一条{delete_object}记录,点击{delete_button_name}；3.系统弹出确认删除提示框，点击确定；",
                    f"1.进入{module}{page_name}页面页面；2.勾选一条{delete_object}记录,点击{delete_button_name}；3.系统弹出确认删除提示框，点击取消；",
                    f"1.进入{module}{page_name}页面页面；2.勾选多条{delete_object}记录,点击{delete_button_name}。",
                ]
                case_expect_result += ["系统应提示请勾选后再进行删除操作"]
                if check_result_method == '0':
                    if total_delete == '是':
                        # 彻底删除
                        # 数据库查看
                        case_expect_result += [
                            f"去数据库查看，该条数据已查询不到",
                            f"去数据库查看，该条数据仍能查询到",
                        ]
                    else:
                        case_expect_result += [
                            f"去数据库查看，该条数据能查询到，但是显示状态改变",
                            f"去数据库查看，该条数据仍能查询到，数据无变化",
                        ]

                elif check_result_method == '1':
                    # 页面查看
                    case_expect_result += [
                        f"{page_name}页面该条记录被删除，记录数减1",
                        f"{page_name}页面该条记录无变动，记录数不变",
                    ]
                elif check_result_method == '2':
                    # 数据库、页面均需查看
                    if total_delete == '是':
                        case_expect_result += [
                            f"{page_name}页面该条记录被删除，记录数减1，去数据库查看，查询不到该数据",
                            f"{page_name}页面该条记录无变动，记录数不变，去数据库查看，该条数据仍能查询到，数据无变化",
                        ]
                    else:
                        case_expect_result += [
                            f"{page_name}页面该条记录被删除，记录数减1，去数据库查看，该条数据能查询到，但是显示状态改变",
                            f"{page_name}页面该条记录无变动，记录数不变，去数据库查看，该条数据仍能查询到，数据无变化",
                        ]
                case_expect_result += [
                    "系统应提示请勾选一条记录再进行删除操作"
                ]
        if multi_delete == '支持':
            case_title += [
                f"批量删除全部{delete_object}记录，确认框点击取消",
                f"批量删除全部{delete_object}记录，确认删除",
                f"批量删除多条{delete_object}记录，确认框点击取消",
                f"批量删除多条{delete_object}记录，确认删除",
                f"不勾选{delete_object}记录，点击批量删除",
            ]
            case_steps += [
                f"1.进入{module}{page_name}页面页面，勾选全部{delete_object}记录；2.点击{multi_delete_button_name},弹出删除确认框；3.点击取消。",
                f"1.进入{module}{page_name}页面页面，勾选全部{delete_object}记录；2.点击{multi_delete_button_name},弹出删除确认框；3.点击确定，勾选的{delete_object}记录被删除，{page_name}页面的当前页、总页数及总记录数同步变更。",
                f"1.进入{module}{page_name}页面页面，勾选多条{delete_object}记录；2.点击{multi_delete_button_name},弹出删除确认框；3.点击取消，关闭删除确认框，数据无变化。",
                f"1.进入{module}{page_name}页面页面，勾选多条{delete_object}记录；2.点击{multi_delete_button_name},弹出删除确认框；3.点击确定，勾选的{delete_object}记录被删除，{page_name}页面的当前页、总页数及总记录数同步变更。",
                f"1.进入{module}{page_name}页面页面，不勾选{delete_object}记录；2.点击{multi_delete_button_name}按钮。",
            ]
            case_expect_result += [
                f"数据无变动",
                f"勾选的记录被全部删除，{page_name}页面的当前页、总页数及总记录数同步变更",
                f"数据无变动",
                f"勾选的记录被全部删除，{page_name}页面的当前页、总页数及总记录数同步变更",
                f"系统应提示请勾选{delete_object}记录后再进行批量操作",
            ]
        if total_delete == '是':
            pass

        project = Project.objects.get(project_name__exact=case_system)
        for _ in range(len(case_title)):
            case.create(
                title=case_title[_], pre_condition=case_precondition,
                case_steps=case_steps[_], primary_module=primary_module, sub_module=sub_module,
                case_level=case_level, creator=case_creator,
                expect_result=case_expect_result[_], project_id=project.id,
                create_time=time.strftime("%Y-%m-%d %H:%M:%S"), remarks='', page='删除'
            )
    return redirect(reverse('app01:delete_page_new_row'))


def component(request):
    cases = Cases.objects.all().filter(page='组件').order_by("-id")
    p = request.GET.get('current_page', 1)
    p = int(p)
    paginator = Paginator(cases, 10)
    projects = Project.objects.all()
    users = User.objects.all()
    page_range = transfer_the_page_range(p, paginator)
    if paginator.num_pages - p > 5:
        last_page = True
    try:
        pages = paginator.page(p)
    except PageNotAnInteger:
        pages = paginator.page(1)
    except EmptyPage:
        pages = paginator.page(paginator.num_pages)
    return render(request, 'app01/component.html', locals())


def component_create_case(request):
    if request.method == 'POST':
        case_title = request.POST.get('case_title')
        pre_condition = request.POST.get('pre_condition')
        case_steps = request.POST.get('case_steps')
        primary_module = request.POST.get("primary_module")
        sub_module = request.POST.get("sub_module")
        creator = request.POST.get('creator')
        expect_result = request.POST.get('expect_result')
        remarks = request.POST.get('remarks')
        create_time = time.strftime('%Y-%m-%d %H:%M:%S')
        level = request.POST.get('level')
        level = int(level)
        case = Cases.objects.all()
        case.create(
            title=case_title, pre_condition=pre_condition, case_steps=case_steps, case_level=level,
            creator=creator, expect_result=expect_result, create_time=create_time, remarks=remarks, page='编辑',
            primary_module=primary_module, sub_module=sub_module,
        )
        return redirect(reverse('app01:component'))


def component_search_case(request):
    return HttpResponse("Not Yet")


def component_edit_case(request):
    return HttpResponse("Not Yet")


def component_generate_case(request):
    return HttpResponse("Not Yet")


def new_row(request):
    templates = Template.objects.all()
    projects = Project.objects.all()
    users = User.objects.all()
    return render(request, 'app01/newRow.html', locals())
    # return HttpResponse("TEST")


def search_page_new_row(request):
    templates = Template.objects.all()
    projects = Project.objects.all()
    users = User.objects.all()
    return render(request, 'app01/search_page_new_row.html', locals())


def delete_page_new_row(request):
    templates = Template.objects.all()
    projects = Project.objects.all()
    users = User.objects.all()
    return render(request, 'app01/delete_page_new_row.html', locals())


def page_import_new_row(request):
    templates = Template.objects.all()
    projects = Project.objects.all()
    users = User.objects.all()
    return render(request, 'app01/page_import_new_row.html', locals())


def edit_page_new_row(request):
    print(request.get_host())
    projects = Project.objects.all()
    templates = Template.objects.all()
    users = User.objects.all()
    return render(request, 'app01/edit_new_row.html', locals())


def jump_to_admin(request):
    print(request.get_host())
    return redirect(f"http://{request.get_host()}/admin/")


def search_page_export_excel(request):
    # 导出excel数据
    # 设置HTTPResponse的类型
    cases = Cases.objects.all().filter(page__exact='查询').order_by('-id')
    excel_postfix = time.strftime("%y%m%d%H%M%S")
    excel_name = f'filename=searchPageCase_{excel_postfix}.xls'
    return export(excel_name, cases)


def search_page_search_result_export(request):
    referer = request.headers.get('Referer')
    params_list = referer.split('&')
    params_dict = {}
    params_list = params_list[1:]
    for param in params_list:
        (key, value) = param.split('=')
        params_dict[key] = value
    start_date = params_dict['start_date']
    end_date = params_dict['end_date']
    case_title = params_dict['case_title']
    case_title = unquote(case_title, 'utf-8').strip("+")
    case_title = case_title.strip()
    case_creator = params_dict['case_creator']
    case_creator = unquote(case_creator, 'utf-8').strip("+")
    case_creator = case_creator.strip()
    if start_date and end_date:
        search_result = Cases.objects.filter(Q(create_time__gte=start_date + " 00:00:00") &
                                             Q(create_time__lte=end_date + " 23:59:59"),
                                             title__contains=case_title,
                                             creator__contains=case_creator,
                                             page__exact='查询').order_by('-id')
    elif start_date:
        search_result = Cases.objects.filter(create_time__gte=start_date + " 00:00:00",
                                             title__contains=case_title,
                                             creator__contains=case_creator,
                                             page__exact='查询').order_by('-id')
    elif end_date:
        search_result = Cases.objects.filter(create_time__lte=end_date + " 23:59:59",
                                             title__contains=case_title,
                                             creator__contains=case_creator,
                                             page__exact='查询').order_by('-id')
    else:
        search_result = Cases.objects.filter(title__contains=case_title,
                                             creator__contains=case_creator,
                                             page__exact='查询').order_by('-id')
    print(type(search_result))
    excel_postfix = time.strftime("%y%m%d%H%M%S")
    excel_name = f'filename=searchPageCase_{excel_postfix}.xls'
    return export(excel_name, search_result)


def page_import_search_result_export(request):
    return HttpResponse("Not Yet!")


def export_page_new_row(request):
    # TODO 导出新建
    projects = Project.objects.all()
    templates = Template.objects.all()
    users = User.objects.all()
    return render(request, 'app01/export_new_row.html', locals())


def export_page_search_result_export(request):
    return HttpResponse("Not Yet")


def delete_page_delete(request):
    return HttpResponse("Not Yet")


def delete_page_search_result_export(request):
    return HttpResponse("Not Yet")


def component_new_row(request):
    return HttpResponse("Not Yet")


def component_export_excel(request):
    return HttpResponse("Not Yet")


def component_delete(request, case_id):
    Cases.objects.get(pk=case_id).delete()
    referer = request.headers.get('Referer')
    return redirect(referer)


def component_search_result_export(request):
    return HttpResponse("Not Yet")


@csrf_exempt
def multi_delete(request):
    # TODO
    if request.method == 'POST':
        ids = request.POST.get('id')
        id_list = ids.split(",")
        print(id_list)
        for case_id in id_list:
            Cases.objects.get(pk=case_id).delete()
        data = {"message": "删除成功"}
    return JsonResponse(data)


def new_page_multi_delete(request):
    # TODO
    return HttpResponse("multi_delete")


def search_page_multi_delete(request):
    # TODO
    return HttpResponse("multi_delete")


def page_import_multi_delete(request):
    # TODO
    return HttpResponse("multi_delete")


def export_page_multi_delete(request):
    # TODO
    return HttpResponse("multi_delete")


def delete_page_multi_delete(request):
    # TODO
    return HttpResponse("multi_delete")


def edit_page_multi_delete(request):
    # TODO
    return HttpResponse("multi_delete")


def component_multi_delete(request):
    # TODO
    return HttpResponse("multi_delete")